每次都是用到,查一下,写下,这次稍微记录下笔记。
#include <pthread.h>
编译得时候需要-lpthread
和Thread相关,基本的有3个概念:线程的建立和销毁;线程锁;线程条件
关于建立线程:
ret = pthread_create(&thread_id, NULL, Do_Thread, &Do_Thread_Para);
// 第2参数是thread 属性,一般我不用设置
// 第4个参数是Do_Thread的入口参数,一般我传一个结构体进去
关于销毁线程:
等待线程结束:pthread_join
强行杀掉线程:pthread_exit
让线程自生自灭:pthread_detach
我一般用的是第一个:
pthread_join(thread_id, &Do_Thread_ret);
// 第二个参数是线程返回值
关于线程锁:当要在多个线程共享某些变量的时候,就需要用锁。这样可以保证一个时间点,只有一个线程能够访问这个线程
pthread_mutex_t mMutexData;
pthread_mutex_init(&(mMutexData), NULL); // 第2个参数是锁的属性,我一般用默认,NULL
pthread_mutex_lock(&mMutexData); // 加锁
pthread_mutex_unlock(&mMutexData) // 去锁
pthread_mutex_destroy(&mMutexData) // 销毁
关于条件:当某个线程需要等待其他线程处理完某个数据(运行到某个点)的话,就需要用条件,一般加个时间参数,以防止死等下去。
pthread_cond_t *sConditionData;
pthread_cond_init(&(sConditionData), NULL); // 第2个参数是锁的属性,我一般用默认,NULL
pthread_mutex_lock(&mMutexData); // 一般条件必须和锁加在一起用,以保证条件变量不重入
pthread_cond_signal(&sConditionData); // 发信号
pthread_mutex_unlock(&mMutexData);
struct timespec ts;
struct timeval sTime;
struct timezone sTimeZone;
long res;
pthread_mutex_lock(&(pApp->mMutexData));
gettimeofday(&sTime, &sTimeZone);
ts.tv_sec = sTime.tv_sec;
ts.tv_nsec += 5sTime. tv_usec * 1000 +20*1000*1000; // 20 ms
ret = pthread_cond_timedwait(&(pApp->sConditionData), &(pApp->mMutexData), &ts); // 等候
if(ret == ETIMEDOUT)
{
pthread_mutex_unlock(&(pApp->mMutexData));
continue;
}
pthread_mutex_unlock(&(pApp->mMutexData));
pthread_cond_destroy(&sConditionData); // 销毁