关于线程的了解,可以阅读前一篇文章《Linux关于多线程技术》,了解线程后,阅读本文章会比较容易
以下代码是想让一个线程count进行累加,另一边读出来,每次累加就读出来一次
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<stdlib.h>
int count = 0;
void *thr1(void *arg)
{
while(1)
{
sleep(1);
count+=10;
}
}
void *thr2(void *arg)
{
while(1)
{
printf("%d\n",count);
}
}
int main()
{
pthread_t tid1,tid2;
pthread_create(&tid1,NULL,thr1,NULL);
pthread_create(&tid2,NULL,thr2,NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
}
但是实际结果却不是这样的,会无限循环,两个线程不会进行同步
下面我们使用信号量,进行PV操作,让线程进行同步
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<stdlib.h>
#include <semaphore.h>
sem_t sem;
int count = 0;
void *thr1(void *arg)
{
while(1)
{
sleep(1);
sem_post(&sem);//V操作
count+=10;
}
}
void *thr2(void *arg)
{
while(1)
{
sem_wait(&sem);//P操作
printf("%d\n",count);
}
}
int main()
{
pthread_t tid1,tid2;
pthread_create(&tid1,NULL,thr1,NULL);
pthread_create(&tid2,NULL,thr2,NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
}
结果如下:实现线程同步