多线程信号量控制

来源:互联网 发布:动态图截取软件 编辑:程序博客网 时间:2024/05/01 01:52

代码关键解释

主线程控制信号量+1,这就是sem_post的作用。

子线程等待信号量,如果不>0,则一直等待,一旦得到信号量是大于0的,代码继续向下执行,并且把信号量-1,这就是sem_wait的作用。

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>

void *thread_function(void *argc);
sem_t bin_sem;

int main()
{
   int res;
   pthread_t a_thread;
   void *thread_return;

   res = sem_init(&bin_sem, 0, 0); //创建信号量,初始化信号量值为0
   if(res != 0)
   {
     perror("Semaphore initialization failed\n");
     exit(EXIT_FAILURE);
   }
   res = pthread_create(&a_thread, NULL, thread_function, NULL); //创建线程
   while (1)
   {
       sleep(1);
       sem_post (&bin_sem);   //信号量+1
   }

   printf("Thread joined\n");
   sem_destroy(&bin_sem); //清理信号量
   return 0;
}

void *thread_function(void *arg) //线程启动执行函数
{
    while (1)
    {
        sem_wait(&bin_sem); //信号量=0时等待,大于0时-1,并向下执行

        printf ("semaphore finally released by main thread\n");
    }
}


 

原创粉丝点击