创建线程
linux中创建POSIX线程的程序如下:
#include <pthread.h>
int pthread_create(thread, attr, start_routine, arg);
注释:start_routine的形式如下,arg是对应的参数,类型为void*
void* start_routine(void*)
{/*程序代码*/}
关于pthread_create函数的说明如下:
thread为指向线程标识符指针,
attr设置线程属性
start_routine是线程运行函数的起始地址
arg是start_routine的参数,它必须通过把引用作为指针强制转换为 void 类型进行传递
终止线程
#include <pthread.h>
pthread_exit(status);
等待线程
pthread_join(tid, NULL);
//在主线程中阻塞,直到线程号为tid的线程结束返回之后,才继续进行
举例说明
以下是一个简单的生成线程的代码:
该实例中利用pthread_create()创建了三个线程
#include <pthread.h>
#include <stdio.h>
#include <iostream>
void* test(void* t)
{
int i = *((int*)t);
printf("thread():: pthread%d is created!\n",i);
}
int main()
{
pthread_t tid[3];
int ret;
for(int i = 0; i < 3; i++)
{
std::cout << "main():: pthread create!" << i + 1 << std::endl;
if((ret = pthread_create(&tid[i], NULL, test, (void*)&(i))) != 0) std::cout << "create error" << std::endl;
}
printf("end of main >>>\n");
pthread_exit(NULL);
}
提示:由于pthread不是linux系统的默认库,所以在编译时候需要添加动态链接,具体如下:
g++ demo.cpp -lpthread -o demo
运行结果如下:
main():: pthread create!1
main():: pthread create!2
main():: pthread create!3
thread():: pthread2 is created!
//个人推测,此处可能是编译做了优化,导致for循环已经执行了一遍之后才创建第一个线程
thread():: pthread2 is created!
end of mian >>>
thread():: pthread3 is created!
main():: pthread create!1
main():: pthread create!2
thread():: pthread1 is created!
main():: pthread create!3
thread():: pthread2 is created!
end of main >>>
thread():: pthread3 is created!
注意:由于多线程的原因,每次运行的结果可能会不一样。
利用pthread_join()函数可以保证多线程的运行流程
示例代码如下:
#include <pthread.h>
#include <stdio.h>
#include <iostream>
void* test(void* t)
{
int i = *((int*)t);
printf("thread():: pthread%d is created!\n",i + 1);
}
int main()
{
pthread_t tid[3];
int ret;
for(int i = 0; i < 3; i++)
{
std::cout << "main():: pthread create!" << i + 1 << std::endl;
if((ret = pthread_create(&tid[i], NULL, test, (void*)&(i))) != 0) std::cout << "create error" << std::endl;
pthread_join(tid[i], NULL);
}
printf("end of main >>>\n");
pthread_exit(NULL);
}
多次运行结果始终如下:
main():: pthread create!1
thread():: pthread1 is created!
main():: pthread create!2
thread():: pthread2 is created!
main():: pthread create!3
thread():: pthread3 is created!
end of main >>>
由此可见,pthread_join()函数可以阻塞当前进程,直至线程号为tid的线程执行完毕之后才会继续该进程的执行。
参考资料:
https://www.runoob.com/cplusplus/cpp-multithreading.html(推荐阅读)
http://www.cppblog.com/tuantuan/archive/2009/08/02/91970.html