C++多线程

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++多线程|菜鸟教程

内容略有改动,全部手敲,只为加深印象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值