关于C++多线程编程的相关知识
std::thread
传入方法:
#include<iostream>
#include <thread>
using namespace std;
void sayHello()
{
for(int i = 0;i<=20;i++){
cout << "hello" <<endl;
}
}
void sayHi(){
for (int i = 0;i<=20;i++){
cout<<"Hi"<<endl;
}
}
int main()
{
thread t1(sayHello);
thread t2(sayHi);
t1.join();
t2.join();
}
传入函数对象:
#include<iostream>
#include <thread>
using namespace std;
class Test1{
public:
void operator()(){
cout << "hello" <<endl;
}
};
class Test2{
public:
void operator()(){
cout << "hi" <<endl;
}
};
int main()
{
Test1 test1;
Test2 test2;
thread t1(test1);
thread t2(test2);
t1.join();
t2.join();
}
传入类的成员变量:
#include<iostream>
#include <thread>
using namespace std;
class Test1{
public:
void sayHello(){
cout << "hello" <<endl;
}
};
class Test2{
public:
void sayHi(){
cout << "hi" <<endl;
}
};
int main()
{
Test1 test1;
Test2 test2;
thread t1(&Test1::sayHello,&test1);
thread t2(&Test2::sayHi,&test2);
t1.join();
t2.join();
}
等待线程完成
使用std::thread 方法中的join()来实现等待线程完成
调用join()的行为,还清理了线程相关的存储部分,这样std::thread
对象将不再与已经完成的线程有任何关联。这意味着,只能对一个线程使用一次join();一旦已经使用过join(),std::thread
对象就不能再次加入了,当对其使用joinable()时,将返回false。
后台运行线程
使用std::thread 方法中的detach()来实现等待线程完成
使用detach()会让线程在后台运行,这就意味着主线程不能与之产生直接交互。也就是说,不会等待这个线程结束;如果线程分离,那么就不可能有std::thread
对象能引用它,分离线程的确在后台运行,所以分离线程不能被加入。不过C++运行库保证,当线程退出时,相关资源的能够正确回收,后台线程的归属和控制C++运行库都会处理。当std::thread
对象使用t.joinable()返回的是true,才可以使用t.detach()
pthread.h
Linux系统下的多线程遵循POSIX线程接口,称为pthread
创建线程
#include <pthread.h>
pthread_create (thread, attr, start_routine, arg)
参数 | 描述 |
thread | 指向线程标识符指针,当一个新的线程调用成功之后,就会通过这个参数将线程的句柄返回给调用者,以便对这个线程进行管理。 |
attr | 一个不透明的属性对象,可以被用来设置线程属性。可以指定线程属性对象,也可以使用默认值 NULL。 |
start_routine | (入口函数)线程运行函数起始地址,一旦线程被创建就会执行。当你的程序调用了这个接口之后,就会产生一个线程,而这个线程的入口函数就是start_routine()。如果线程创建成功,这个接口会返回0。 |
arg | 入口函数的参数。它必须通过把引用作为指针强制转换为 void 类型进行传递。如果没有传递参数,则使用 NULL。 |
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg);
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>
using namespace std;
#define NUM_THREADS 5
void *wait(void *t)
{
....
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);
rc = pthread_create(&threads[i], NULL, wait, (void *)&i );
.....
pthread_exit(NULL);
}
终止线程
#include <pthread.h>
pthread_exit (status)
参考链接:
https://www.cnblogs.com/duan-shui-liu/p/11430290.html
https://www.runoob.com/cplusplus/cpp-multithreading.html
https://www.cnblogs.com/douzujun/p/10810506.html
https://www.cnblogs.com/linxw-blog/p/10455450.html
https://www.jianshu.com/p/ffd2108d0697
https://blog.csdn.net/networkhunter/article/details/100218945