线程同步

来源:互联网 发布:win域名需要备案吗 编辑:程序博客网 时间:2024/06/05 17:59
 

用信号量进行同步:

信号量一般常用于保护一段代码,使其每次只能被一个线程执行,要完成这个工作,就要使用二进制信号量。

信号量函数的名字都以sem_开头,线程中使用的信号量函数有四个

信号量通过sem_init函数创建

#include<semaphore.h>

Int sem_init(sem_t *sem,int pshared,unsigned int value);

两个函数控制信号量的值

#include<semaphore.h>

int sem_wait(sem_t  *sem);以原子操作减1,但它会等待直到信号量有非零值才会开始减法操作,如果对值0信号量调用sem_wait,这个函数就会等待,直到有其他线程增加了该信号量的值使其不再为0为止。

int sem_post(sem_t  *sem );信号量加1,是以原子操作的方式给信号量加1,所谓原子操作室指,如果两个线程企图同时给信号量加1,他们之间不会互相干扰,而不像两个程序同时对同一个文件进行读取,增加,写入操作则会引起冲突,信号量总是会被正确的加2.

#include<semaphore.h>

int  sem_destory(sem_t *sem);

清理该信号量拥有的所有资源

这些函数在成功时返回0。

/*thread_sem.c*/

#include<stdio.h>

#include<unistd.h>

#include<stdlib.h>

#include<string.h>

#include<pthread.h>

#include<semaphore.h>

void *thread_function(void *arg);

#define WORK_SIZE 1024

char work_area[WORK_SIZE];

 

sem_t bin_sem;

 

int main()

{

       int res;

       pthread_t a_thread;

       void *thread_result;

       res=sem_init(&bin_sem,0,0);

       if(res!=0)

       {

              perror("semaphore initilization failed\n");

              exit(EXIT_FAILURE);

       }

       res=pthread_create(&a_thread,NULL,thread_function,NULL);

       if(res!=0)

       {

              perror("thread creation failed");

              exit(EXIT_FAILURE);

       }

       printf("input some text.enter 'end' to finish\n");

       while(strncmp("end",work_area,3)!=0)

       {

              fgets(work_area,WORK_SIZE,stdin);

              sem_post(&bin_sem);

       }

       printf("\nwaiting for thread to finish...\n");

       res=pthread_join(a_thread,&thread_result);

       if(res!=0)

       {

              perror("thread join failed");

              exit(EXIT_FAILURE);

       }

       printf("thread joind\n");

       sem_destroy(&bin_sem);

       exit(EXIT_SUCCESS);

}

 

 

void *thread_function(void *arg)

{

       sem_wait(&bin_sem);

       while(strncmp("end",work_area,3)!=0)

       {

              printf("you input %d characters\n",strlen(work_area)-1);

              sem_wait(&bin_sem);

       }

       pthread_exit(NULL);

}

原创粉丝点击