C++多线程
直接进入正题,如何使用c++多线程。
1. 使用pthread
需要包含头文件pthread
:
#include<pthread.h>
1.1 创建线程
使用pthread_create
函数,使用语法如下:
pthread_create(thread,attr,start_routine,arg);
参数介绍:
参数 | 说明 |
---|---|
thread | 指向线程标识符指针 |
attr | 一个不透明的属性对象,可以被用来设置线程属性。可以指定线程属性对象,也可以使用默认值NULL |
start_routine | 线程运行函数起始地址,一旦线程被创建就会执行。 |
arg | 执行函数的参数。它必须通过把应用作为指针强制转换为void 类型进行传递,如果没有传递参数,则使用NULL . |
注意:
创建线程成功时,函数返回0,若返回值不为0,则说明创建线程失败。
示例
#include <iostream>
#include <pthread.h>
using namespace std;
void* say_hello(void* args){
cout << "Hello Pthread..." << endl;
}
int main() {
pthread_t pt;
int ret = pthread_create(&pt,NULL,say_hello,NULL);
if(ret == 0){
cout << "线程创建成功。。。" << endl;
}
else {
cout << "线程创建失败。。。 " << endl;
}
return 0;
}
注意
这里运行时可能会报pthread_create
未定义使用,这是因为pthread
库不是Linux
系统默认的库,连接时需要使用库libpthrea.a
,所以在使用pthread_create
创建线程时,请使用终端编译,指令如下:
g++ main.cpp -lpthread -o main
./main
输出结果为:
Hello Pthread...
线程创建成功。。。
1.2 终止线程
使用函数pthread_exit
,语法如下:
pthread_exit(status);
在这里,pthread_exit
用于显示地推出一个线程。通常情况下,pthread_exit
函数是在线程完成工作之后无需继续存在时被调用。如果main是在它所创建的线程之前结束,并通过pthread_exit
退出,那么其他线程将继续执行,否则他们将在main结束时自动被终止。
示例:
#include <iostream>
#include <pthread.h>
using namespace std;
void* say_hello(void* args){
cout << "Hello Pthread..." << endl;
}
int main() {
pthread_t pt[5];//创建一个数组,保存线程id
//创建5个线程
for(int i = 0;i < 5;i++){
int ret = pthread_create(&pt[i],NULL,say_hello,NULL);
if(ret != 0){
cout << "线程创建失败。。。" << endl;
}
}
//等各个线程退出后,进程才结束,否则进程强制结束了,线程可能还没反应过来
pthread_exit(NULL);
return 0;
}
执行如下指令:
g++ main.cpp -lpthread -o main
./main
#结果如下
Hello Pthread...
Hello Pthread...
Hello Pthread...
Hello Pthread...
Hello Pthread...
1.3向线程传递参数
示例
#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
#define NUM_THREADS 5
struct thread_data{
int thread_id;
char *message;
};
void* say_hello(void *threadarg){
struct thread_data *my_data;
my_data = (struct thread_data*)threadarg;
cout << "thread id:" << my_data->thread_id << endl;
cout << "message:" << my_data->message << endl;
pthread_exit(NULL);
}
int main(){
pthread_t threads[NUM_THREADS];
struct thread_data td[NUM_THREADS];
int rc;
int i;
for(i = 0;i < NUM_THREADS;i++){
cout << "main():creating thread," << i << endl;
td[i].thread_id = i;
td[i].message = (char*)"this is message";
rc = pthread_create(&threads[i],NULL,say_hello,(void*)&td[i]);
if(rc){
cout << "创建线程失败。。" << endl;
exit(-1);
}
}
pthread_exit(NULL);
}
要注意的是:传入的参数必须转换为无类型指针
执行如下指令:
g++ main.cpp -lpthread -o main
./main
#结果如下
main():creating thread,0
main():creating thread,1
main():creating thread,2
thread id:0
thread id:1
message:this is message
message:this is message
thread id:2
message:this is message
main():creating thread,3
main():creating thread,4
thread id:3
message:this is message
thread id:4
message:this is message
1.4连接和分离线程
使用pthread_join
函数连接线程,pthread_join
子程序阻塞调用线程,直到指定的threadid
线程终止为止。当创建一个线程时,它的某个属性会定义它是否是可连接的或可分离的。只有创建时定义为可连接的线程才可以被连接。如果线程创建时被定义为可分离,则它永远也不能被连接。
使用pthread_detach
函数分离线程。
示例:
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>
using namespace std;
#define NUM_THREADS 5
void *wait(void *t)
{
int i;
long tid;
tid = (long)t;
sleep(1);
cout << "Sleeping in thread " << endl;
cout << "Thread with id : " << tid << " ...exiting " << endl;
pthread_exit(NULL);
}
int main ()
{
int rc;
int i;
pthread_t threads[NUM_THREADS];
pthread_attr_t attr;
void *status;
// 初始化并设置线程为可连接的(joinable)
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for( i=0; i < NUM_THREADS; i++ ){
cout << "main() : creating thread, " << i << endl;
rc = pthread_create(&threads[i], NULL, wait, (void *)&i );
if (rc){
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
// 删除属性,并等待其他线程
pthread_attr_destroy(&attr);
for( i=0; i < NUM_THREADS; i++ ){
rc = pthread_join(threads[i], &status);
if (rc){
cout << "Error:unable to join," << rc << endl;
exit(-1);
}
cout << "Main: completed thread id :" << i ;
cout << " exiting with status :" << status << endl;
}
cout << "Main: program exiting." << endl;
pthread_exit(NULL);
}
2.使用标准线程库thread
示例
#include <iostream>
#include <thread>
using namespace std;
thread::id main_thread_id = this_thread::get_id();
void hello(){
cout << "hello thread" << endl;
if(main_thread_id == this_thread::get_id()){
cout << "this is main thread." << endl;
}
else{
cout << "this is not the main thread." << endl;
}
}
void pause_thread(int n){
this_thread::sleep_for(chrono::seconds(n));
cout << "pause of " << n << " seconds ended." << endl;
}
int main(){
thread t(hello);
//可以并发执行多少个(不准确)
cout << t.hardware_concurrency() << endl;
//可以并发执行多少个(不准确)
cout << "native_handle" << t.native_handle() << endl;
//连接线程
t.join();
thread a(hello);
//分离线程
a.detach();
//调用默认构造函数
thread threads[5];
cout << "Spawning 5 threads..." << endl;
for (int i = 0;i < 5;i++){
threads[i] = thread(pause_thread,i+1);
}
cout << "Done spawning threads.Now waiting for them to join." << endl;
for(auto &thread : threads){
thread.join();
}
cout << "All threads joined." << endl;
}
执行如下指令
g++ -std=c++11 main.cpp -lpthread -o main
./main
#运行结果如下
12
native_handle139670510393088
hello thread
this is not the main thread.
Spawning 5 threads...
hello thread
this is not the main thread.
Done spawning threads.Now waiting for them to join.
pause of 1 seconds ended.
pause of 2 seconds ended.
pause of 3 seconds ended.
pause of 4 seconds ended.
pause of 5 seconds ended.
All threads joined.
参考自:C++多线程|菜鸟教程
内容略有改动,全部手敲,只为加深印象。