嵌入式Linux应用程序开发——多线程4(线程的同步——信号量)
2019-07-13 05:05发布
生成海报
#include
#include
#include
#include
#include
int global;
sem_t sem_test1,sem_test2;
void *thread_function(void *arg)
{
int i,j;
for(i=0;i<10;i++)
{
sem_wait(&sem_test2);/*阻塞当前线程直到信号量的值大于0*/
j = global;
j = j+1;
global = j;
printf("-");
fflush(stdout);
sem_post(&sem_test1);/*增加信号量的值*/
}
return NULL;
}
int main()
{
pthread_t th_new;
int i,ret;
if((ret=sem_init(&sem_test1,0,0))!=0)/*初始化信号量*/
perror("sem_test1_init");
if((ret=sem_init(&sem_test2,0,0))!=0)/*初始化信号量*/
perror("sem_test2_init");
if(pthread_create(&th_new,NULL,thread_function,NULL))
{
perror("error creating thread");
abort();
}
for(i=0;i<10;i++)
{
global++;
printf("m");
fflush(stdout);
sem_post(&sem_test2);
sem_post(&sem_test1);
}
if(pthread_join(th_new,NULL))
{
perror("error joining thread");
abort();
}
printf("
result is:%d
",global);
sem_destroy(&sem_test1);
sem_destroy(&sem_test2);
exit(0);
}
打开微信“扫一扫”,打开网页后点击屏幕右上角分享按钮