1. 程式人生 > >Linux主執行緒接收資料,子執行緒分別對其操作後輸出

Linux主執行緒接收資料,子執行緒分別對其操作後輸出

本例子雖小,但是融合的執行緒同步,執行緒回收和訊號量的知識。

需要注意pthread_join()和pthread_exit()的用法和區別:

pthread_join一般是主執行緒來呼叫,用來等待子執行緒退出,因為是等待,所以是阻塞的,一般主執行緒會依次join所有它建立的子執行緒。
pthread_exit一般是子執行緒呼叫,用來結束當前執行緒。
子執行緒可以通過pthread_exit傳遞一個返回值,而主執行緒通過pthread_join獲得該返回值,從而判斷該子執行緒的退出是正常還是異常。

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

sem_t bin_sem;
int data;

void *thread_functionB(void *arg);
void *thread_functionA(void *arg);

int main(void)
{
	int res;
	pthread_t a_thread;
	pthread_t b_thread;
	void *thread_resultA;
	void *thread_resultB;
	if(sem_init(&bin_sem, 0, 0))
	{
		printf("sem init error!\n");
		exit(EXIT_FAILURE);
	}
	res = pthread_create(&a_thread, NULL, thread_functionA, NULL);
	if(res != 0)
	{
		perror("Thread creation failed");
		exit(EXIT_FAILURE);
	}
	res = pthread_create(&b_thread, NULL, thread_functionB, NULL);
	if(res != 0)
	{
		perror("thread creation failed!");
		exit(EXIT_FAILURE);
	}
	//sem_wait(&bin_sem);
	printf("input a number:\n");
	scanf("%d",&data);
	sem_post(&bin_sem);
	if(pthread_join(a_thread, &thread_resultA)!=0)
	{
		perror("thread a join error!");
		exit(EXIT_FAILURE);
	}
	if(pthread_join(b_thread, &thread_resultB)!=0)
	{
		perror("thread b join error!");
		exit(EXIT_FAILURE);
	}
	printf("thread A has joined, it returned:%s\n", (char *)thread_resultA);
	printf("thread B has joined, it returned:%s\n", (char *)thread_resultB);
	printf("final data is:%d\n", data);
	exit(EXIT_SUCCESS);
}

void *thread_functionA(void *arg)
{
	sem_wait(&bin_sem);
	data++;
	printf("thread A ++\n");
	sem_post(&bin_sem);
	pthread_exit("thread A has exited");
}
void *thread_functionB(void *arg)
{
	sem_wait(&bin_sem);
	data++;
	printf("thread B ++\n");
	sem_post(&bin_sem);
	pthread_exit("thread B has exited");
}

編譯並執行結果正確: