Commit be0c7a98 authored by Sven Gestegård Robertz's avatar Sven Gestegård Robertz
Browse files

thread example mutex_init

parent e68956fa
......@@ -12,12 +12,11 @@
struct global_data{
int count;
pthread_mutex_t mtx;
sem_t sem_a;
sem_t sem_b;
};
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
void * task_a(void * ctx)
{
struct global_data *d = ctx;
......@@ -26,10 +25,10 @@ void * task_a(void * ctx)
printf("started task_a\n");
for(i=0; i < d->count; ++i){
sem_wait(&d->sem_a);
pthread_mutex_lock(&mtx);
pthread_mutex_lock(&d->mtx);
printf("task_a: %d\n",i);
sem_post(&d->sem_b);
pthread_mutex_unlock(&mtx);
pthread_mutex_unlock(&d->mtx);
}
return NULL;
}
......@@ -42,10 +41,10 @@ void * task_b(void * ctx)
printf("started task_b\n");
for(i=0; i < d->count; ++i){
sem_wait(&d->sem_b);
pthread_mutex_lock(&mtx);
pthread_mutex_lock(&d->mtx);
printf("task_b: %d\n",i);
sem_post(&d->sem_a);
pthread_mutex_unlock(&mtx);
pthread_mutex_unlock(&d->mtx);
}
return NULL;
}
......@@ -53,6 +52,7 @@ void * task_b(void * ctx)
int global_data_init(struct global_data *d)
{
d->count = 10;
pthread_mutex_init(&d->mtx, NULL);
if(sem_init(&d->sem_a, 0, 0)){
return 1;
}
......@@ -85,10 +85,10 @@ int main()
exit(3);
}
sleep(1);
pthread_mutex_lock(&mtx);
pthread_mutex_lock(&data.mtx);
printf("signalling semaphore\n");
sem_post(&data.sem_a);
pthread_mutex_unlock(&mtx);
pthread_mutex_unlock(&data.mtx);
pthread_join(thread_a, NULL);
pthread_join(thread_b, NULL);
return 0;
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment