利用互斥量和信号量对创建的多个线程之间的调度进行控制
如果不进行控制,就会有多个线程同时获取到同一个数据,并对其进行操作。
例如让多个线程打印1-1000,不加锁有可能会打印两个相同的数。
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<assert.h>
#include<pthread.h>
#include<semaphore.h>
int g = 1;
sem_t sem;
pthread_mutex_t mutex;//创建互斥锁
void* fun(void*arg)
{
int i = 0;
for(;i<1000;i++)
{
//sem_wait(&sem);//使用信号量进行的p操作
pthread_mutex_lock(&mutex);
printf("g=%d\n",g++);
//sem_post(&sem);//使用信号量进行的V操作
pthread_mutex_unlock(&mutex);
}
}
int main()
{
pthread_t id[5];
//sem_init(&sem,0,1);//初始化信号量
pthread_mutex_init(&mutex,NULL);//初始化锁
int i = 0;
for(;i<5.i++)
{
pthread_create(&id[i],NULL.fun.NULL);//创建线程
}
for(i = 0;i<5;i++)
{
pthread_join(id[i],NULL);//获取结束线程id
}
//sem_destroy(&sem);
pthread_mutex_destroy(&mutex);//销毁锁
exit(0);
}
循环打印ABC
使用三个线程sem1,sem2,sem3分别打印ABC,使用信号量控制打印顺序
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<assert.h>
#include<pthread.h>
#include<semaphore.h>
sem_t sem1;
sem_t sem2;
sem_t sem3;
void*fun_A(void* arg)
{
int i = 0;
for(;i<5;i++)
{
sem_wait(&sem1);//P操作
wirte(1,"A",1);
sem_post(&sem2);//V操作
}
}
void* fun_B(void* arg)
{
int i = 0;
for(;i<5;i++)
{
sem_wait(&sem2);
write(1,"B",1);
sem_post(&sem3);
}
}
void* fun_C(void* arg)
{
int i = 0;
for(;i<5;i++)
{
sem_wait(&sem3);
write(1,"C",1)
sem_post(&sem1);
}
}
int main()
{
pthread_t id[3];
sem_init(&sem1,0,1);
sem_init(&sem2,0,0);
sem_init(&sem3,0,0);
pthread_create(&id[0],NULL,fun_A,NULL);
pthread_create(&id[1],NULL,fun_B,NULL);
pthread_create(&id[2],NULL,fun_C,NULL);
pthread_join(id[0],NULL);
phtread_join(id[1],NULL);
pthread_join(id[2],NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
sem_destroy(&sem3);
exit(0);
}