Q1: 创建一个子线程,传入数值1,在子线程中能够获取并打印,子线程退出,返回数值2,主线程通过pthread_join获取等待子线程结束并获取子线程的退出值并打印。
#include <func.h>
void* threadFunc(void* p)
{
printf("I am child thread %d\n",*(int*)p);
pthread_exit((void*)2);
}
int main(int argc,char* argv[])
{
pthread_t pthid;
int ret;
int val=1;
ret=pthread_create(&pthid,NULL,threadFunc,&val);
THREAD_ERROR_CHECK(ret,"pthread_create");
long threadRet;
pthread_join(pthid,(void**)&threadRet);
THREAD_ERROR_CHECK(ret,"pthread_join");
printf("I am main pthread, %ld\n",threadRet);
return 0;
}
Q2: 创建一个子线程,子线程申请内存,通过清理函数进行free,子线程停留在read标准输入,主线程cancel子线程,子线程能够通过清理函数free对应的malloc的内存。
#include <func.h>
void cleanup(void* p)
{
free(p);
printf("free sucess\n");
}
void* threadFunc(void* p)
{
char buf[128];
p=malloc(100);
pthread_clean_up(cleanup,p);
read(STDIN_FILENO,buf,128);
pthread_cleanup_pop(1);
pthread_exit(NULL);
}
int main(int argc,char* argv[])
{
pthread_t pthid;
int ret;
ret=pthread_create(&pthid,NULL,threadFunc,NULL);
THREAD_ERROR_CHECK(ret,"pthread_create");
ret=pthread_cancel(pthid);
THREAD_ERROR_CHECK(ret,"pthread_cancel");
long threadRet;
ret=pthread_join(pthid,(void**)&threadRet);
THREAD_ERROR_CHECK(ret,"pthread_join");
printf("I am main pthread %ld\n",threadRet);
return 0;
}
Q3: 创建一个子线程,cancel子线程,在子线程中push两个清理函数,感受清理函数的执行顺序。
#incldue <func.h>
void cleanup1(void* p)
{
printf("I am cleanup1\n");
}
void cleanup2(void* p)
{
printf("I am cleanup2\n");
}
void* threadFunc(void* p)
{
pthread_cleanup_push(cleanup1,p);
pthread_cleanup_push(cleanup2,p);
sleep(1);
pthread_cleanup_pop(1);
pthread_cleanup_pop(1);
}
int main(int argc,char* argv[])
{
pthread_t pthid;
int ret;
ret=pthread_create(&pthid,NULL,threadFunc,NULL);
THREAD_ERROR_CHECK(ret,"pthread_create");
ret=pthread_cancel(pthid);
THREAD_ERROR_CHECK(ret,"pthread_cancel");
long threadRet;
ret=pthread_join(pthid,(void**)&threadRet);
THREAD_ERROR_CHECK(ret,"pthread_join");
printf("I am main thread %d\n",threadRet);
return 0;
}
Q4: 子线程,主线程,同时对一个全局变量加2千万,通过加锁,实现最终效果是4千万。
#include <func.h>
#define N 20000000
typedef struct{
int val;
pthread_mutex_t mutex;
}Data_t;
void* threadFunc(void* p)
{
int i;
Data_t *pVal = (Data_t*)p;
for(i=0;i<N;i++)
{
pthread_mutex_lock(&pVal->mutex);
pVal->val+=1;
pthread_mutex_unlock(&pVal->mutex);
}
}
int main(int argc,char* argv[])
{
pthread_t pthid;
int ret;
Data_t threadInfo;
threadInfo.val=0;
ret=pthread_mutex_init(&threadInfo.mutex,NULL);
THREAD_ERROR_CHECK(ret,"pthread_mutex_init");
struct timeval start, end;
gettimeofday(&start,NULL);
ret=pthread_create(&pthid,NULL,threadFunc,&threadInfo);
THREAD_ERROR_CHECK(ret,"pthread_create");
int i;
for(i=0;i<N;i++)
{
pthread_mutex_lock(&threadInfo.mutex);
threadInfo.val+=1;
pthread_mutex_unlock(&threadInfo.mutex);
}
pthread_join(pthid,NULL); //等待子线程
gettimeofday(&end,NULL);
printf("I am main pthread,val=%d,use_time=%ld\n",threadInfo.val,(end.tv_sec-start.tv_sec)*1000000+end.tv_usec-start.tv_usec);
return 0;
}