本例子虽小,但是融合的线程同步,线程回收和信号量的知识。
需要注意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);