”多线程+信号量+互斥锁“ 亲测可用的简单demo

来源:互联网 发布:淘宝矫正牙套管不管用 编辑:程序博客网 时间:2024/05/21 17:26
/*requirment: pthread0 prints string before pthread1*/#include <stdio.h>#include <stdlib.h>#include <pthread.h>#include <semaphore.h>pthread_mutex_t mutex;sem_t sem;int source=10;void pthread0(void){    while(1)    {pthread_mutex_lock(&mutex);source=0;pthread_mutex_unlock(&mutex);printf("this is thread0 and the source is %d\n",source);sem_post(&sem);sleep(2);    }}void pthread1(void){    while(1)    {sem_wait(&sem);pthread_mutex_lock(&mutex);source=1;pthread_mutex_unlock(&mutex);printf("this is thread1 and the source is %d\n",source);sleep(2);    }}void main(){    pthread_t id0;    pthread_t id1;    sem_init(&sem,0,0);    pthread_mutex_init(&mutex,NULL);    pthread_create(&id0,NULL,(void*)pthread0,NULL);    pthread_create(&id1,NULL,(void*)pthread1,NULL);    while(1)    {printf("this is main function\n");sleep(2);    }    pthread_join(id0,NULL);    pthread_join(id1,NULL);}