线程的使用

本文详细介绍了C++中创建线程的不同方式,包括std::thread类的使用,通过函数指针、函数对象、lambda函数以及C++98中的pthread函数。此外,还涵盖了线程常用方法如线程对象的构造、析构、join、detach操作,以及std::this_thread命名空间提供的功能。
摘要由CSDN通过智能技术生成

目录

1,创建线程的几种方式

2,示例

3,线程常用方法

3.1 std::thread类

3.1.1 成员变量

3.1.2 thread成员函数

3.1.2.1 thread 构造函数

3.1.2.2 thread 析构函数

3.1.2.3 get_id 获取线程id

3.1.2.4 joinable 

3.1.2.5 join 加入

3.1.2.6 detach 分离

3.1.2.7 swap 交换线程

3.1.2.8 join用法示例

3.1.2.9 detach()用法示例

3.2 std::this_thread命名空间

3.2.1 this_thread命名空间的函数介绍

3.3 pthread函数 (C++98)

3.3.1 pthread_create 线程创建 

3.3.2 pthread_join线程挂起

3.3.3 pthread_exit线程退出

3.3.4 pthread_self获取当前线程id

3.3.5 代码示例


1,创建线程的几种方式

        a> 通过函数指针创建线程

        b> 通过函数对象创建线程

        c> 通过lambda函数创建线程

使用std::thread类创建对象,必须包含头文件

        #include <thread>

创建的形式是

        std::thread thobj(<CALL_BACK>)

        新线程将在创建新对象后立即启动,并将与启动该线程的线程并行执行传递的回调。而且,任何线程都可以通过在该线程的对象上调用join()函数来等待另一个线程退出。

2,示例

        std::this_thread::sleep_for 函数是休眠函数,表示当前线程休眠一段时间,休眠期间不与其他线程竞争CPU

        std::chrono::seconds 是 std::chrono 库中的一个持续时间类

        std::cref、std::ref 和 std::reference_wrapper
        在 C++ 编程中,有时候我们需要在不进行拷贝的情况下传递引用,或者在需要引用的地方使用常量对象。为了解决这些问题,C++ 标准库提供了三个有用的工具:std::cref、std::ref 和 std::reference_wrapper。
        std::cref 是一个模板函数,用于创建对常量对象的引用。它返回一个 std::reference_wrapper 对象,可以在需要引用的地方使用。这在函数参数传递中特别有用,因为它允许我们在不进行拷贝的情况下传递常量对象,同时保持引用的语义。
      std::ref 是一个模板函数,用于创建对可修改对象的引用。它返回一个 std::reference_wrapper 对象,允许我们在需要引用的地方使用,同时允许修改被引用的对象。
        std::reference_wrapper 是一个模板类,用于包装引用,使其能够在容器中存储或以引用的形式传递。它提供类似引用的语法,并且可以与标准容器一起使用,因为容器无法直接存储引用。

#include <iostream>
#include <thread>
#include <chrono>
using namespace std;

class Thread_Test
{
public:
	void operator()()
	{
		for (int i = 0; i < 5; i++)
		{
			cout << "class Thread_Test is running..." << endl;
			std::this_thread::sleep_for(std::chrono::seconds(2));
		}
	}

	void FunctionInner(int m)
	{
		for (int j = 0; j < m; j++)
		{
			cout << "class FunctionInner thread is running..." << endl;
			std::this_thread::sleep_for(std::chrono::seconds(2));
		}
	}
};

void thread_func( int m )
{
	for (int i = 0; i < m; ++i) {
		cout << " thread thread_func is running..." << endl;
		std::this_thread::sleep_for(std::chrono::seconds(1));
	}
}

int main()
{
	// 1.普通函数
	int nPara = 3;
	std::thread obj_thread1(thread_func, std::cref(nPara));
	cout << "thread_func() thread running..." << endl;
	obj_thread1.join();
	cout << "main enter class thread" << endl;
	// 2.仿函数创建
		// 方法一
	/*  thread obj_thread((Thread_Test()));  */
		// 方法二
	Thread_Test c_thread2;
	thread obj_thread(c_thread2);
	cout << "main thread running..." << endl;
	obj_thread.join();
	cout << "main enter thread2 running..." << endl;

	// 普通成员函数
	Thread_Test c_thread3;
	int num = 2;
	thread obj_thread2(&Thread_Test::FunctionInner, &c_thread3, std::cref(num));
	obj_thread2.join();
	cout << "lambda thread is entry" << endl;

	// 3.lambda 表达式创建
	std::thread obj_thread3([]{
		for (int i = 0; i < 3; i++)
		{
			cout << "lambda thread is running..." << endl;
			std::this_thread::sleep_for(std::chrono::seconds(3));
		}
	});
	obj_thread3.join();
	cout << "main thread is exit" << endl;
	return 0;
}

3,线程常用方法

        <thread>头文件包含了std::thread类和std::this_thread命名空间的声明。C++开发中include <thread>头文件,就可以使用std:thread线程类std::this_thread命名空间,std::this_thread这个命名空间包含了对当前线程的一些基本操作,如获取当前线程id、休眠当前线程、让渡当前线程的时间片给其他线程等。

3.1 std::thread类

        std::thread类来表示执行的各个线程。执行线程是实际上是执行一系列指令,可以在多线程环境中与其他此类序列同时执行,同时共享相同的地址空间。

        一个初始化的线程(std::thread)对象表示活动的执行线程,即初始化后std::thread立即运行;这样的线程对象是可连接的(joinable),并且具有唯一的线程id。默认构造的(未初始化的)线程对象是不可连接的(not joinable),其线程id对于所有不可连接线程都是通用的。

        如果move线程,或者对它们调用join或detach,则可连接线程将变得不可连接。

3.1.1 成员变量

       id

                Thread id (public member type)

        native_handle_type

                Native handle type (public member type)

示例:

#include <thread>
#include <chrono>
#include <iostream>
using namespace std;

void thread_func(int m)
{
    for (int i = 0; i < m; ++i) {
        cout << " thread thread_func is running..." << endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}

int main()
{
    int nPara = 3;
    std::thread obj_thread1(thread_func, std::cref(nPara));
    // thread 成员变量 id
    std::thread::id f_id = obj_thread1.get_id();
    cout << "thread_func() thread running..." << endl;
    obj_thread1.join();
    cout << "main exit thread" << endl;

    return 0;
}

3.1.2 thread成员函数

        Construct thread // 构造函数
        thread destructor // 析构函数
        operator=// 赋值重载
        get_id // 获取线程id
        joinable// 判断线程是否可以加入等待
        join//Join thread (public member function ) 加入等待
        detach//Detach thread (public member function ) 分离线程
        swap//Swap threads (public member function ) 线程交换
        native_handle// 获取线程句柄
        hardware_concurrency // 检测硬件并发特性
        swap (thread)
        Swap threads (function )

3.1.2.1 thread 构造函数

        a>  默认构造函数,创建一个空的 thread 执行对象。

        b> 普通构造函数,初始化构造函数,创建一个 thread对象,该 thread对象可被 joinable,新产生的线程会调用 fn 函数,该函数的参数由 args 给出。

        c> 拷贝构造函数(被禁用),意味着 thread 不可被拷贝构造。
        d> move 构造函数(移动分配线程函数),move 构造函数,调用成功之后 x 不代表任何 thread 执行对象。

拷贝构造函数  (被禁)

// 函数原型
thread(const thread&) = delete;
thread& operator=(const thread&) = delete;

// 错误 示例代码
thread t3(t1);
thread t4 = t1;

移动分配线程函数

// 代码原型
thread& operator=(thread&& _Other) noexcept
thread(thread&& _Other) noexcept
// 正确的示例代码
thread t5 = std::move(t1);
thread t6(std::move(t1));

 示例:

#include <thread>
#include <chrono>
#include <iostream>
using namespace std;

class Thread_Test
{
public:
    void operator()()
    {
        for (int i = 0; i < 5; i++)
        {
            cout << "class Thread_Test is running..." << endl;
            std::this_thread::sleep_for(std::chrono::seconds(2));
        }
    }

    void FunctionInner(int m)
    {
        for (int j = 0; j < m; j++)
        {
            cout << "class FunctionInner thread is running..." << endl;
            std::this_thread::sleep_for(std::chrono::seconds(2));
        }
    }
};

void thread_func(int m)
{
    for (int i = 0; i < m; ++i) {
        cout << " thread thread_func is running..." << endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}

int main()
{
    int nPara = 3;
    // a, 默认构造函数
    std::thread t1; 
    // b, 构造函数构造
        /* 通过值构造 */
    std::thread t2(thread_func, nPara);
        /* 通过引用构造 */
    std::thread t3(thread_func, std::cref(nPara));
        /* 仿函数指针构造 */
    std::thread t4((Thread_Test()));
        /* 通过仿函数对象构造 */
    Thread_Test c_thread2;
    std::thread t5(c_thread2);
        /* 通过普通成员函数构造 */
    Thread_Test c_thread3;
    int num = 2;
    std::thread t6(&Thread_Test::FunctionInner, &c_thread3, std::cref(num));
    // d, move
    // t7 is now running . t3 is no longer a thread
    std::thread t7(std::move(t3));

    t2.join();
    t4.join();
    t5.join();
    t6.join();
    t7.join();

    cout << "main exit class thread" << endl;

    return 0;
}
3.1.2.2 thread 析构函数

        当线程对象被销毁时,它会自动调用析构函数,如果线程没有被join()或detach(),则程序会终止并抛出std::terminate异常。

// 不调用join()或detach()
// 当my_thread对象离开作用域时会抛出std::terminate异常
std::thread t2(thread_func, nPara);
3.1.2.3 get_id 获取线程id
 cout << "thread1' id is " << t1.get_id() << endl;
3.1.2.4 joinable 

判断线程是否可连接

bool joinable() const noexcept;

检查线程是否可连接,返回线程对象是否可连接。

(1)如果线程对象表示执行线程,则它是可连接的。

(2)在以下任何情况下,线程对象都不可连接:

                a, 如果它是默认构造的。

                b, 如果它已被move(构造另一个线程对象,或分配给另一个线程)。

                c, 如果已调用其成员join或detach。

示例:

if (false == t7.joinable())
{
    cout << "[error] : t7 is not join! " << endl;
}
else
{
    cout << "t7 is join... " << endl;
    t7.join();
}
3.1.2.5 join 加入

        连接线程,阻塞调用线程

                void join();

        连接(join)线程,当线程执行完成时,函数返回。

        join()函数能够保证调用线程和被调用线程同步,join()函数将阻塞调用该join()函数线程的执行,直到被调用线程的函数返回。调用join()函数后,线程对象变得不可连接,可以安全销毁。

3.1.2.6 detach 分离

        分离线程,调用线程和被调用线程各自独立运行

                void detach();

        分离(detach)线程将对象表示的线程与调用线程分离,允许它们彼此独立地执行。

        这两个线程都继续运行,不会以任何方式阻塞或同步。请注意,当其中一方结束执行时,其资源将被释放。调用此函数后,线程对象变得不可连接,可以安全销毁。

3.1.2.7 swap 交换线程

        void swap (thread& x) noexcept;

        交换线程,将对象的状态与x的状态交换。

        swap函数与thread的移动构造函数和移动赋值函数作用一样。

示例

cout << "thread1' id is " << t1.get_id() << endl;
cout << "thread2' id is " << t2.get_id() << endl;

cout << "swap after:" << endl;
swap(t1, t2);//线程交换
cout << "thread1' id is " << t1.get_id() << endl;
cout << "thread2' id is " << t2.get_id() << endl;
3.1.2.8 join用法示例
#include <iostream>       // std::cout
#include <thread>         // std::thread
void foo() 
{  // do stuff... }
 
void bar(int x)
{  // do stuff... }
 
int main() 
{
  std::thread first (foo);    
  std::thread second (bar,0);  
  first.join();                // pauses until first finishes
  second.join();               // pauses until second finishes 
  return 0;
}
3.1.2.9 detach()用法示例
#include <iostream>       // std::cout
#include <thread>         // std::thread, std::this_thread::sleep_for
#include <chrono>         // std::chrono::seconds
 
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::cout << "Spawning and detaching 3 threads...\n";
  std::thread (pause_thread,1).detach();
  std::thread (pause_thread,2).detach();
  std::thread (pause_thread,3).detach();
  std::cout << "Done spawning threads.\n";
 
  std::cout << "(the main thread will now pause for 5 seconds)\n";
  // give the detached threads time to finish (but not guaranteed!):
  pause_thread(5);
  return 0;
}

输出:

Spawning 5 threads...
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!

3.2 std::this_thread命名空间

        此命名空间提供了访问当前线程的一组函数。

3.2.1 this_thread命名空间的函数介绍

        get_id     获得当前线程id

        Yield      将当前线程时间片让渡给其他线程

        sleep_until 当前线程休眠直到某个时间点

        sleep_for   当前线程休眠一段时间

3.3 pthread函数 (C++98)

3.3.1 pthread_create 线程创建
 

函数原型

int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict attr,void *(*start_rtn)(void),void *restrict arg);

  返回值:若是成功建立线程返回0,否则返回错误的编号。
  形式参数:pthread_t *restrict tidp要创建的线程的线程id指针;

                        const pthread_attr_t *restrict attr创建线程时的线程属性;

                        void* (start_rtn)(void)返回值是void类型的指针函数;

                        void *restrict arg start_rtn的形参。

3.3.2 pthread_join线程挂起

  该函数的作用使得当前线程挂起,等待另一个线程返回才继续执行。也就是说当程序运行到这个地方时,程序会先停止,然后等线程id为thread的这个线程返回,然后程序才会断续执行。
  函数原型:

int pthread_join( pthread_t thread, void **value_ptr);

参数说明如下:thread等待退出线程的线程号;

                        value_ptr退出线程的返回值。


3.3.3 pthread_exit线程退出

        函数原型

void pthread_exit(void *rval_ptr);

3.3.4 pthread_self获取当前线程id

        函数原型

pthread_t pthread_self(void);

3.3.5 代码示例

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
void *thread(void *ptr)
{
    int i;
    for(i=0;i<3;i++){
        sleep(1);
    printf("This is a pthread.\n");}
}
int main(void)
{
    pthread_t id;
    int i,ret;
    
    ret=pthread_create(&id,NULL,thread,NULL);
    if(ret!=0){
        printf ("Create pthread error!\n");
        exit (1);
    }

    for(i=0;i<3;i++){
        printf("This is the main process.\n");
        sleep(1);
    }
    
    pthread_join(id,NULL);
    
    return (0);
}
 
编译链接命令 g++ -o example2 example.c -lpthread
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值