Skip to content

Instantly share code, notes, and snippets.

@indutny

indutny/sem.cc Secret

Created August 22, 2012 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indutny/81c3620a29d9e55fcc72 to your computer and use it in GitHub Desktop.
Save indutny/81c3620a29d9e55fcc72 to your computer and use it in GitHub Desktop.
#include <pthread.h>
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <assert.h>
#include <mach/mach_init.h>
#include <mach/task.h>
#include <mach/thread_act.h>
#include <mach/semaphore.h>
static semaphore_t sem;
static semaphore_t a_done;
static thread_act_t a_act;
void* ThreadA(void* arg) {
a_act = mach_thread_self();
semaphore_signal(a_done);
fprintf(stdout, "wait!\n");
fprintf(stdout, "%d\n", semaphore_wait(sem));
fprintf(stdout, "wait end!\n");
return NULL;
}
void* ThreadB(void* arg) {
semaphore_wait(a_done);
sleep(1);
return NULL;
}
int main() {
pthread_t a, b;
semaphore_create(mach_task_self(), &sem, 0, 0);
semaphore_create(mach_task_self(), &a_done, 0, 0);
pthread_create(&a, NULL, ThreadA, NULL);
pthread_create(&b, NULL, ThreadB, NULL);
sleep(1);
pthread_cancel(a);
pthread_join(a, NULL);
pthread_join(b, NULL);
semaphore_destroy(mach_task_self(), sem);
semaphore_destroy(mach_task_self(), a_done);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment