一、pthread_create()函数
1、定义:
int pthread_create(pthread_t * thread, const pthread_attr_t * attr, void * ( * start_routine ) ( void * ), void * arg)
2、作用:
创建一个新的子线程,然后该子线程会执行
start_routine()函数。若线程创建成功,则返回0。若线程创建失败,则返回出错编号。
3、参数:
thread:保存创建的新的子线程的线程号,同一个进程中的每一个线程的线程号是不相同的,但是不同的进程中的线程的线程号可以相同;
attr:设置创建的线程的属性 一般设置为NULL,表示使用默认属性;
start_rotine:线程的执行函数,也就是线程创建成功之后执行的函数。(注:该参数的类型是一个函数指针)
arg:传递给start_rotine()函数的参数。
4、注意:
使用线程函数的时候除了需要引入头文件
#include <pthread.h>,还需要在编译的时候链接线程的线程库文件g++ -o xxx xxx.cpp -lpthread
二、pthread_join()函数
1、定义:
int pthread_join(pthread_t thread, void **retval)
2、作用:
让当前线程等待指定的线程结束,并且当等待的线程结束之后就回收该线程的资源。若成功,则返回0;若失败,返回的是错误号。
3、参数:
thread:要等待的线程的线程id;
retval:接收等待的线程结束时的返回值。
4、注意:
根据等待的线程是否结束,可能有两种情况:
1 等待的线程尚未结束,则pthread_join()会陷入阻塞;
2 等待的线程已经结束,则pthread_join()会将线程的返回值(void *类型)存放到retval指针所指向的位置,并且回收该线程的资源。
三、程序实例:
#include <iostream>
#include <pthread.h>
#include <string>
#include <ctime>
#include <unistd.h>
using namespace std;
void* run(void *num)
{
for(int i = 1; i < 100; i += 2)
{
cout << pthread_self() << ' ' << i << endl;
sleep(1);
}
return nullptr;
}
int main()
{
pthread_t pid;
void* (*frun) (void*) = run;
pthread_create(&pid, nullptr, frun, nullptr);
cout << pthread_self() << endl;
/*srand(time(nullptr));
while(1)
{
cout << rand() % 10000 << endl;
sleep(1);
}*/
pthread_join(pid, nullptr);
return 0;
}
博客介绍了Linux环境下C++多线程编程的两个函数。pthread_create用于创建新子线程,需注意编译时链接线程库;pthread_join让当前线程等待指定线程结束并回收资源,根据等待线程状态可能阻塞或回收资源,还给出了程序实例。
11万+

被折叠的 条评论
为什么被折叠?



