Linux线程同步之信号量

信号量

​ 信号量可以同时访问多份资源。

#include 
int sem_init(sem_t* sem, int pshared, unsigned int value);
int sem_destroy(sem_t* sem);
int sem_post(sem_t* sem);
int sem_wait(sem_t* sem);
int sem_trywait(sem_t* sem);
int sem_timedwait(sem_t* sem, const struct timespec* abs_timeout);

sem_init:

​ sem是创建信号量对象地址 , pshared代表是否可以与fork出的子进程共享资源(0代表不可共享 , 1代表可共享),value代表初始状态下的资源数。

sem_destroy:

​ 销毁信号量。

sem_post:

​ 信号量的资源计数递增1。当时用sem_wait函数的话就会被唤醒。

sem_trywait:

​ 不断去尝试唤醒,如果失败,就会发回EAGAIN错误码。

sem_timewait:

​ sem_timedwait 在参数 abs_timeout设置的时间内等待信号量对象的资源计数大于0,否则超时返回,返回值为 ﹣1,错误码 ETIMEDOUT。当使用 sem_timedwait 时,参数 abs_timeout 不能设置为 NULL,否则程序会在运行时调用 sem_timedwait 产生崩溃。

struct timespec
{
    time_t tv_sec;      /* 秒 */
    long   tv_nsec;     /* 纳秒 [0 .. 999999999] */
};

实例代码

#include 
#include 
#include 
#include 
pthread_mutex_t  mymutex;
sem_t            mysemaphore;
int global = 0;
int global_c = 0;

void *Consumer_thread(void *para){
	pthread_t *tid = (pthread_t*)para;
	printf("-------- Consumer_threadID%d-------\n" , tid);
	while(1){
		pthread_mutex_lock(&mymutex);
		
		global_c++;
		printf("Consumer__pthread :global_c = %d\n" , global_c);
		
		pthread_mutex_unlock(&mymutex);
		sleep(1);	
		printf("sleep(1)\n");
	}
	return NULL;
}

void *Producer_pthread(void *para){

	printf("*****Producer_pthread*****\n");
	while(1){

		sem_post(&mysemaphore);
		global++;
		printf("Producer_pthread :global = %d\n" , global);

		sleep(1);
		printf("sleep(5)\n");
	}
	return NULL;
}

int main(int argc, const char *argv[])
{
	int i = 0;
	pthread_mutex_init(&mymutex , NULL);
	sem_init(&mysemaphore , 1 , 0);
	pthread_t Consumer_pthreadID[5];
	for(i = 0; i < 5 ;i++ ){
		pthread_create(&Consumer_pthreadID[i] , NULL , Consumer_thread , &Consumer_pthreadID[i]);
	}
	
	pthread_t Producer_pthreadID;
	pthread_create(&Producer_pthreadID , NULL , Producer_pthread , NULL);

	pthread_join(Producer_pthreadID , NULL);
	for(i = 0 ; i < 5 ; i++){
		pthread_join(&Consumer_pthreadID , NULL);
	}

	sem_destroy(&mysemaphore);
	pthread_mutex_destroy(&mymutex);
	return 0;
}

调试结果

linux@linux:/mnt/hgfs/ubuntushare/pthread$ ./a.out 
*****Producer_pthread*****
Producer_pthread :global = 1
-------- Consumer_threadID-1076573684-------
Consumer__pthread :global_c = 1
-------- Consumer_threadID-1076573688-------
Consumer__pthread :global_c = 2
-------- Consumer_threadID-1076573692-------
Consumer__pthread :global_c = 3
-------- Consumer_threadID-1076573696-------
Consumer__pthread :global_c = 4
-------- Consumer_threadID-1076573700-------
Consumer__pthread :global_c = 5
sleep(5)
Producer_pthread :global = 2
sleep(1)
Consumer__pthread :global_c = 6
sleep(1)
Consumer__pthread :global_c = 7
sleep(1)
Consumer__pthread :global_c = 8
sleep(1)
Consumer__pthread :global_c = 9
sleep(1)
Consumer__pthread :global_c = 10
^C

你可能感兴趣的:(LInux多线程编程)