一、线程连接的作用
int pthread_join(pthead_t tid, void **rval)
1、调用该函数的线程会一直阻塞,直到指定的线程tid调用pthread_exit、从启动例程返回或者被取消。
参数tid就是指定线程的id。
参数rval是指定线程的返回码,如果线程被取消,那么rval被置为PTHREAD_CANCELED。
该函数调用成功会返回0,失败返回错误码。
2、调用pthread_join会使指定的线程处于分离状态,如果指定线程已经处于分离状态,那么调用就会失败。
pthread_detach
可以分离一个线程,线程可以自己分离自己。
int pthread_detach(pthread_t thread);
成功返回0,失败返回错误码
二、实例
1、程序框架
2、源代码
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <iostream>
#include "include/pthread.h"
#ifndef _WIN64
#pragma comment(lib,".\\lib32\\pthreadVC2.lib")
#else
#pragma comment(lib,".\\lib64\\pthreadVC2.lib")
#endif
/*
*pthread_join(pthread_t tid,void **rval);
* 调用该函数线程会阻塞,直到线程tid终止,而且会使tid分离
* 如果tid已经分离,那么调用pthread_join就会失败
*pthreaddetach(pthreadt, tid)
* 分离有tid指定的线程
*
*/
void* thread_fun1(void* arg) {
printf("I'm thread1\n");
return (void*)0;
}
void* thread_fun2(void* arg) {
printf("I'm thread1\n");
pthread_detach(pthread_self());
pthread_exit((void*)0);
return (void*)0;
}
int main()
{
int err1,err2;
pthread_t tid1,tid2;
void* rval1, *rval2;
err1 = pthread_create(&tid1,NULL,thread_fun1,NULL);
err2 = pthread_create(&tid2,NULL,thread_fun2,NULL);
if (err1 || err2)
{
printf("creat new thread failed\n");
return 0;
}
printf("I'am main thread\n");
printf("join1 rval is %d\n",pthread_join(tid1,&rval1));
printf("join2 rval is %d\n",pthread_join(tid2,&rval2));
printf("thread 1 exit code is %d \n",(int*)rval1);
printf("thread 2 exit code is %d \n",(int*)rval2);
printf("I'am main thread\n");
system("pause");
return 0;
}
三、练习
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <iostream>
#include "include/pthread.h"
#ifndef _WIN64
#pragma comment(lib,".\\lib32\\pthreadVC2.lib")
#else
#pragma comment(lib,".\\lib64\\pthreadVC2.lib")
#endif
/*
*DESCRIPTION: 一个线程被连接成功后,另一个线程就不能再连接该线程了
* int pthread_join(pthead_t tid, void **rval)
调用该函数的线程会一直阻塞,直到指定的线程tid调用pthread_exit、从启动例程返回或者被取消
*/
int err;
pthread_t tid1, tid2;
void* thread_fun1(void* arg) {
//睡眠1s,让线程2先执行
Sleep(1);
printf("I'm new thread1\n");
pthread_exit((void *)0);
return (void*)0;
}
void* thread_fun2(void* arg) {
printf("I'm new thread2\n");
//连接线程1
err = pthread_join(tid1, NULL);
if (err != 0)
{
printf("new thread2 join thread 1 failed\n");
}
else
{
printf("new thread2 join thread 1 success\n");
}
pthread_exit((void *)0);
return (void*)0;
}
int main()
{
//创造新线程
err = pthread_create(&tid1, NULL, thread_fun1, NULL);
if (err!=0)
{
printf("creat new thread 1 failed\n");
return 0;
}
//创造新线程2
err = pthread_create(&tid2, NULL, thread_fun2, NULL);
if (err != 0)
{
printf("creat new thread 2 failed\n");
return 0;
}
//连接线程1
err = pthread_join(tid1, NULL);
if (err!=0)
{
printf("main thread join thread 1 failed\n");
}
else
{
printf("main thread join thread 1 success\n");
}
system("pause");
return 0;
}