在C语言中使用Pthread库
我有以下代码:在C语言中使用Pthread库,c,pthreads,producer-consumer,C,Pthreads,Producer Consumer,我有以下代码: #include<stdio.h> #include<pthread.h> int mutex=1,i=0,full=0; void p(int *s) { while(*s<=0) ; *s--; } void v(int *s) { *s++; } void *producer() { p(&mutex); printf("Producer is producing\n");
#include<stdio.h>
#include<pthread.h>
int mutex=1,i=0,full=0;
void p(int *s)
{
while(*s<=0)
;
*s--;
}
void v(int *s)
{
*s++;
}
void *producer()
{
p(&mutex);
printf("Producer is producing\n");
v(&mutex);
v(&full);
}
void *consumer()
{
p(&full);
p(&mutex);
printf("Consuming\n");
v(&mutex);
}
int main()
{
pthread_t thread1,thread2;
int k;
for(k=0;k<10;k++)
{
pthread_create(&thread1,NULL,(void *(*)(void *))producer,NULL);
pthread_create(&thread2,NULL,(void *(*)(void *))consumer,NULL);
}
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
}
#包括
#包括
int mutex=1,i=0,full=0;
无效p(int*s)
{
虽然(*s通过共享变量进行线程间同步几乎肯定是个坏主意,但即便如此,共享变量至少应该声明为volatile
考虑使用实数同步原语,例如或实数
您在此处使用术语“互斥体”是不正确的;它不是互斥体。互斥体应在同一线程中锁定和释放,并用于阻止其他线程访问资源。如果这不是您想要的行为,则互斥体是错误的原语-可能您需要一个信号量而不是互斥体。代码是错误的有太多的方法无法理解正在发生的事情。这两个问题突然出现在我的脑海中
i--和i++不是原子操作,因此互斥或full都没有您认为的值
您正在创建20个线程,但仅在最后两个线程上连接
代码中没有内存障碍,因此SMP系统中内存更改的顺序实际上是未定义的
*s--
表示*(s--)
不是(*s)--