自学内容网 自学内容网

线程互斥函数的例子

代码

#include<stdio.h>
#include<pthread.h>
#include<sched.h>
void *producter_f(void *arg);
void *consumer_f(void *arg);
int buffer_has_item=0;
pthread_mutex_t mutex;
int running=1;
int main(void)
{
pthread_t consumer_t;
pthread_t producter_t;
pthraed_mutex_init(&mutex,NULL);
pthread_create(&producter_t,NULL,(void*)producter_f,NULL);
pthread_create(&consumer_t ,NULL,(void*)consumer_f,NULL);
usleep(1);
running =0;
pthread_join(consumer_t,NULL);
pthread_join(producter_t,NULL};
pthread_mutex_destroy(&mutex);
return 0;
}
void *producter_f(void *arg)
{
while(running)
{
pthread_mutex_lock(&mutex);
buffer_has_item++;
printf("product,total num:%d\n",buffer_has_item);
pthread_mutex_unlock(&mutex);
}
}
void *consumer_f(void *arg)
{
while(running)
{
pthread_mutex_lock(&mutex);
buffer_has_item--;
printf("consumer,total num:%d\n",buffer_has_item);
pthread_mutex_unlock(&mutex);
}
}

运行:


原文地址:https://blog.csdn.net/chenbingjy/article/details/142712233

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!