#include
#include
#include
#include
#include
#include
#include
#include
#include
//g++ -g -o pthread pthread.cpp -lpthread void *thread(void *str) { int i; // pthread_detach(pthread_self()); //和pthread_join不同,两者取其一 分离线程,不管主函数有没有运行完,线程都会运行完毕 for (i = 0; i < 10; ++i) { sleep(2); printf( "This in the thread : %d\n" , i ); } return NULL; } int main() { pthread_t pth; int i; pthread_create(&pth, NULL, thread, NULL); pthread_join(pth, NULL); //等待子线程运行完毕 如果没有这行,两个线程相混,如果主函数运行完毕了,子线程被迫退出了 for (i = 0; i < 10; ++i) { sleep(1); printf( "This in the main : %d\n" , i ); } pthread_exit(0); return 0; }
//返回:成功为0,失败则返回错误代码
第一个参数是指向pthread_t类型数据的指针。这个指针指向的变量中将被写入一个标识符,用该标识为引用新线程。
第二个参数用于设置线程的属性。一般不需要特殊的属性,设置为NULL。
最后两个参数分别告诉线程将要启动执行的函数和传递给该函数的参数。
void *(*start_routine)(void *);必须要传递一个函数地址,该函数以一个指向void的指针为参数,返回的也是一个指向void的指针
3.void pthread_exit(void *retval);
pthread_exit函数:终止执行;终止调用它的线程并返回一个指向某个对象的指针。注意,绝不能用它来返回一个指向局部变量的指针,因为线程调用该函数后,这个局部变量就不再存在了,这将引起严重的程序漏洞。
//pthread_exit(0);
4.int pthread_join(pthread_t th, void **thread_return); //返回:成功为0,失败为错误代码
pthread_join函数:在线程中的作用等价于进程中用来收集子进程信息的wait函数。
第一个参数指定了将要等待的线程,线程通过pthread_create返回的标识符来指定。
第二个参数是一个指针,它指向另一个指针,而后者指向线程的返回值。
//pthread_join用来等待一个线程的结束,线程间同步的操作。以阻塞的方式等待thread指定的线程结束。
5. pthread_detach(pthread_self());
//pthread_detach最好是放在线程启动函数的第一句
有pthread_join函数的运行结果;等待线程结束后运行主函数
去掉pthread_join和pthread_exit的运行结果;两个相混,并主函数运行完毕后子线程被迫关闭
使用pthread_detach和
pthread_exit的运行结果;相混,等待线程都运行完毕