多线程 是 Linux 编程必备。编程接口上 自然是支持 最多的 POSIX pthread.
1.线程的产生: pthread_create 可以立刻运行一个 void * thread_func(void *) 的线程。
2.线程通讯: 互斥保护 pthread_mutex_t, 条件信号 pthread_cond_t.
pthread_mutex_t 和widnows下的CRITICAL_SECTION 完全相同。
但是看文档 cond用起来 怪怪的。
a. cond 无论广播 还是 单个触发信号, 都针对正在等待cond的线程有效。 如果触发之后,线程再等待则无效。 (why?)
b. cond 等待 还要一个mutex 配合。 (不明白,其中的道理)
倒是 semaphore, 发现这个和widnows下的表现最一致。
测试程序
1. 子线程 等待 信号量
2. 主线程 调用 sem_destroy 是否 会 使 等待的线程产生错误。
测试结果
LINUX下, 子线程不受sem_destroy 的影响。 一直处于等待状态。
#include <iostream>
#include <map>
using namespace std;
#include <semaphore.h>
#include <sys/unistd.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <mqueue.h>
sem_t g_sem;
const char * ret_msg[] =
{
"sem thread exit!",
"cond thread exit!",
"que thread exit!"
};
const char * in_msg[] = { "t1", "t2", "t3"} ;
void *thread_sem(void *arg)
{
int iwait ;
sleep( 1 );
printf(" [1]child_sem is running. Argument was %s\n", (char *)arg );
printf(" [1]If main destroy sem, child wait will return? \n" );
printf(" [1]child_sem waiting for sem.......... \n" );
iwait = sem_wait( &g_sem );
if ( iwait == 0 )
{
printf(" [1]child_sem waiting return OK! \n" );
}
else
{
printf(" [1]child_sem waiting return error! %d\n", iwait );
}
pthread_exit( (void *)ret_msg[0] );
}
int main()
{
int res, ifunc, csel;
pthread_t t1, t2, t3;
void *thread_result;
sem_init( &g_sem , 0, 0 );
printf("create thread_sem \n");
res = pthread_create(&t1, NULL, thread_sem, (void *)in_msg[1]);
sleep( 2 );
printf("\n\ninput \n1.destroy\n2.sem_post \nTo see what happens!...\n");
do
{
csel = getchar();
}while( csel == '\n' );
printf("\nyou choose: %c\nwhat happens here!\n", csel );
if ( csel == '1')
{
ifunc = sem_destroy( &g_sem );
printf( "Destroy semaphore: %d\n", ifunc );
}
else
{
ifunc = sem_post( &g_sem );
printf( "Post semaphore: %d\n", ifunc );
}
printf("join Thread_sem .......\n");
res = pthread_join( t1, &thread_result);
printf("Thread_sem joined, %d %s\n", res, (char *)thread_result);
exit(EXIT_FAILURE);
}