首页 > 编程语言 >C++多线程

C++多线程

时间:2022-11-21 14:23:31浏览次数:48  
标签:std 多线程 thread void C++ 线程 pthread include

c++多线程

多线程其实非常简单

多线程是多任务处理的一种特殊形式,多任务处理允许让电脑同时运行两个或两个以上的程序。一般情况下,两种类型的多任务处理:基于进程和基于线程。

创建线程

#include <pthread.h>
pthread_create (thread, attr, start_routine, arg) 
//创建一个 POSIX 线程
/*
thread 指向线程标识符指针
attr 一个不透明的属性对象,可以被用来设置线程属性。您可以指定线程属性对象,也可以使用默认值 NULL
start_routine 线程运行函数起始地址,一旦线程被创建就会执行
arg 运行函数的参数。它必须通过把引用作为指针强制转换为 void 类型进行传递。如果没有传递参数,则使用 NULL
*/

终止线程

#include <pthread.h>
pthread_exit (status) 
//终止一个 POSIX 线程
/*
在这里,pthread_exit 用于显式地退出一个线程。通常情况下,pthread_exit() 函数是在线程完成工作后无需继续存在时被调用。

如果 main() 是在它所创建的线程之前结束,并通过 pthread_exit() 退出,那么其他线程将继续执行。否则,它们将在 main() 结束时自动被终止。
*/

实例

#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
#define NUM_THREADS     5
void *PrintHello(void *threadid)
{  
   int tid = *((int*)threadid);
   cout << "线程ID, " << tid << endl;
   pthread_exit(NULL);
}
int main ()
{
   pthread_t threads[NUM_THREADS];
   int indexes[NUM_THREADS];
   int rc;
   int i;
   for( i=0; i < NUM_THREADS; i++ ){      
      cout << " 创建线程, " << i << endl;
      indexes[i] = i; 
      rc = pthread_create(&threads[i], NULL,  PrintHello, (void *)&(indexes[i]));
      if (rc){
         cout << "无法创建线程," << rc << endl;
         exit(-1);
      }
   }
   pthread_exit(NULL);
}

向线程传递参数

#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
#define NUM_THREADS 5
struct thread_data{
   int  thread_id;
   char *message;
};
void *PrintHello(void *threadarg)
{
   struct thread_data *my_data;
   my_data = (struct thread_data *) threadarg;
   cout << "Thread ID : " << my_data->thread_id ;
   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,
                          PrintHello, (void *)&td[i]);
      if (rc){
         cout << "Error:unable to create thread," << rc << endl;
         exit(-1);
      }
   }
   pthread_exit(NULL);
}

这个实例演示了如何通过结构传递多个参数。

连接和分离线程

//我们可以使用以下两个函数来连接或分离线程
pthread_join (threadid, status)
pthread_detach (threadid)

这个实例演示了如何使用 pthread_join() 函数来等待线程的完成。

#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;
   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);
}

c++11后的标准的线程库

#include <iostream>

#include <thread>

std::thread::id main_thread_id = std::this_thread::get_id();

void hello()  
{
    std::cout << "Hello Concurrent World\n";
    if (main_thread_id == std::this_thread::get_id())
        std::cout << "This is the main thread.\n";
    else
        std::cout << "This is not the main thread.\n";
}

void pause_thread(int n) {
    std::this_thread::sleep_for(std::chrono::seconds(n));
    std::cout << "pause of " << n << " seconds ended\n";
}

int main() {
    std::thread t(hello);
    std::cout << t.hardware_concurrency() << std::endl;
    std::cout << "native_handle " << t.native_handle() << std::endl;
    t.join();
    std::thread a(hello);
    a.detach();
    std::thread threads[5];

    std::cout << "Spawning 5 threads...\n";
    for (int i = 0; i < 5; ++i)
        threads[i] = std::thread(pause_thread, i + 1);
    std::cout << "完成生成线程,现在正等待加入:\n";
    for (auto &thread : threads)
        thread.join();
    std::cout << "All threads joined!\n";
}

标签:std,多线程,thread,void,C++,线程,pthread,include
From: https://www.cnblogs.com/demc/p/16905702.html

相关文章

  • [排序算法] 基数排序 (C++)
    基数排序解释基数排序基数排序RadixSort是一种非基于比较的排序算法。在基数排序中,和计数排序、桶排序的思想类似,我们要再次用到桶这个东西。......
  • 【Java】JDK5.0新增的创建多线程的方式:实现Callable接口,使用线程池
    1.实现Callable接口方式和实现Runnable接口相比call()可以有返回值。call()可以抛出异常,被外面的操作捕获,获取异常信息。Callable是支持泛型的。实现Callable接口......
  • C++初阶(vector容器+模拟实现)
    迭代器四种迭代器容器类名::iterator迭代器名;//正向迭代器容器类名::const_iterator迭代器名;//常量正向迭代器,const修饰,只能用于读取容器内的元素,不能改变其值容......
  • 用C/C++开发工业软件适合吗?
    用C/C++开发工业软件最适合的了,这是因为C/C++是仅次于汇编语言的最底层程序开发语言;同时工业软件最大的特征就是专业性强、复杂度高,需要相当深的专业知识、经验、科研基础,并......
  • C++ using 编译指令与名称冲突
    using编译指令:它由名称空间名和它前面的关键字usingnamespace组成,它使名称空间中的所有名称都可用,而不需要使用作用域解析运算符。在全局声明区域中使用using编译指......
  • effectiveC++1、2
    条款01视C++为一个语言联邦​ 在学习c++高效编程时会出现“所有的适当用法都有例外”的情况,解决的方法是:不把c++当作一门语言,而是将其视为以下四门主要次语言组成的联邦......
  • [排序算法] 桶排序 (C++)
    桶排序解释桶排序思想桶排序是一种空间换取时间的排序方式,是非基于比较的。桶排序顾名思义,就是构建多个映射数据的桶,将数据放入桶内,对每个桶内元素进行单独排序。假设......
  • C++PrimerPlus中文第六版第8章编程练习答案
    1、#include<iostream>#include<string>usingnamespacestd;voidshow(constchar*str,intn=0);constintSize=50;intmain(){chars[Size]="te......
  • [排序算法] 计数排序 (C++)
    计数排序解释计数排序思想计数排序的思想十分简单,就是统计每个数字出现的次数。它是一种非基于比较的排序算法,其是通过额外的空间换取时间的方式,来实现更加高效的排序。......
  • [C++学习笔记-IO控制_1]:IO类
    目录C++IO类C++IO类C++IO跟Linux一样,也是使用缓冲区来提高输入输出的效率,所以在使用的时候也要注意缓冲区这一点。如上图所示,C++中跟输入输出相关的类如下:io......