线程编程出现如下错误:
undefined reference to ‘pthread_create’
undefined reference to ‘pthread_join’
问题原因:
pthread 库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a,所以在使用pthread_create()创建线程,以及调用 pthread_atfork()函数建立fork处理程序时,需要链接该库。
问题解决:
在编译中要加 -lpthread参数
gcc thread.c -o thread -lpthread
thread.c为你些的源文件,不要忘了加上头文件#include<pthread.h>
join()使用
std::thread th(funcPtr);
// 一些其它代码
th.join();
eg.1
cout << "Hello "<< endl;
thread([&]{cout << "thread1" << endl;}).join();
thread t1(fun);
t1.join();
cout << " World"<< endl;
detach()使用
std::thread th(funcPtr);
// 一些其它代码
th.detach();
eg.2
thread([&]{cout << "thread2" << endl;}).detach();
std::this_thread::sleep_for(std::chrono::seconds(5));
std::this_thread::sleep_for()使用:阻塞线程
eg.3
std::this_thread::sleep_for(std::chrono::seconds(5));
时间的使用
using namespace std::chrono_literals;
auto start = std::chrono::high_resolution_clock::now();//获取当前时间
std::this_thread::sleep_for(2s);//等待2s
auto end = std::chrono::high_resolution_clock::now();//获取当前时间
std::chrono::duration<double, std::milli> elapsed = end-start;//过去时间差
std::cout << "运行时间" << elapsed.count() << " s\n";
条件变量(condition_variable)
#include<condition_variable>
通知wait()取消对线程的阻塞有:
notify_one() ->通知第一个进入阻塞或者等待的线程。
notify_broadcast()->通知全部进入阻塞或者等待的线程。
wait()用法:等待进程
std::condition_variable condition;
std::unique_lock<std::mutex> lk(m);
//子进程的中wait函数对互斥量进行解锁,同时线程进入阻塞或者等待状态。
condition.wait(lk, []{return ready;});
notify_one() 和notify_broadcast()用法:解阻塞进程,和wait()一起用
condition.notify_one();
condition.notify_all();
eg.3
//condition_.wait();
//condition_.notify_one();//解阻塞一个进程
//condition_.notify_all();//解阻塞所有进程
std::mutex queueMutex;
std::condition_variable condition_;
thread t3([&]{
std::cout << "fun 1" << std::endl;
std::unique_lock<std::mutex> lock(queueMutex);
condition_.wait(lock,[]{return i==1;});
std::cout << "wait 1" << std::endl;
});
thread t4([&]{
std::cout << "fun 2" << std::endl;
condition_.notify_one();// 等待线程被通知 true condition_.wait 唤醒,检查 i ,再回到等待
std::cout << "wait 2" << std::endl;
i = 1;
condition_.notify_one();// 等待线程被通知 true , cv.wait 返回
});
t3.join();
t4.join();
eg.4
//线程池
#include <iostream>
#include <thread>
#include <vector>
#include <queue>
#include <functional>
#include <mutex>
#include <shared_mutex>
#include <condition_variable>
class ThreadPool
{
public:
ThreadPool(int numThreads) : stop(false)
{
for (int i = 0; i < numThreads; ++i)
{
workers.emplace_back([this] {
while (true)
{
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(queueMutex);
condition.wait(lock, [this] { return stop || !tasks.empty(); });
if (stop && tasks.empty())
return;
task = std::move(tasks.front());
tasks.pop();
}
task();
}
});
}
}
template <class F>
void enqueue(F&& f)
{
{
std::unique_lock<std::mutex> lock(queueMutex);
tasks.emplace(std::forward<F>(f));
}
condition.notify_one();
}
~ThreadPool()
{
{
std::unique_lock<std::mutex> lock(queueMutex);
stop = true;
}
condition.notify_all();
for (std::thread& worker : workers)
worker.join();
}
private:
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex queueMutex;
std::condition_variable condition;
bool stop;
};
void taskFunction(int taskId)
{
std::cout << "Executing task " << taskId << " in thread " << std::this_thread::get_id() << std::endl;
// 模拟耗时任务
std::this_thread::sleep_for(std::chrono::seconds(1));
}
int main()
{
ThreadPool threadPool(4);
for (int i = 0; i < 8; ++i)
{
threadPool.enqueue([i] { taskFunction(i); });
}
// 等待所有任务执行完毕
std::this_thread::sleep_for(std::chrono::seconds(3));
return 0;
}
g++ -std=c++17 thread.cpp -o thread -lpthread
问题解决:
在编译中要加 -lpthread参数
gcc thread.c -o thread -lpthread
thread.c为你些的源文件,不要忘了加上头文件#include<pthread.h>
std::thread detach()与join()用法总结
两者区别
声明std::thread后,都可以使用detach和join函数来启动被调线程,区别在于两者是否阻塞主调线程。
(1)当使用join()函数时,主调线程阻塞,等待被调线程终止,然后主调线程回收被调线程资源,并继续运行;
(2)当使用detach()函数时,主调线程继续运行,被调线程驻留后台运行,主调线程无法再取得该被调线程的控制权。当主调线程结束时,由运行时库负责清理与被调线程相关的资源。
detach()
detach调用之后,目标线程就成为了守护线程,驻留后台运行,与之关联的std::thread对象失去对目标线程的关联,无法再通过std::thread对象取得该线程的控制权。当线程主函数执行完之后,线程就结束了,运行时库负责清理与该线程相关的资源。
当一个thread对象到达生命期终点而关联线程还没有结束时,则thread对象取消与线程之间的关联,目标线程线程则变为分离线程继续运行。
当调用join函数时,调用线程阻塞等待目标线程终止,然后回收目标线程的资源。
detach是使主线程不用等待子线程可以继续往下执行,但即使主线程终止了,子线程也不一定终止。
detach()函数是子线程的分离函数,当调用该函数后,线程就被分离到后台运行,主线程不需要等待该线程结束才结束
join()
join()函数是一个等待线程完成函数,主线程需要等待子线程运行结束了才可以结束
(1)谁调用了这个函数?调用了这个函数的线程对象,一定要等这个线程对象的方法(在构造时传入的方法)执行完毕后(或者理解为这个线程的活干完了!),这个join()函数才能得到返回。
(2)在什么线程环境下调用了这个函数?上面说了必须要等线程方法执行完毕后才能返回,那必然是阻塞调用线程的,也就是说如果一个线程对象在一个线程环境调用了这个函数,那么这个线程环境就会被阻塞,直到这个线程对象在构造时传入的方法执行完毕后,才能继续往下走,另外如果线程对象在调用join()函数之前,就已经做完了自己的事情(在构造时传入的方法执行完毕),那么这个函数不会阻塞线程环境,线程环境正常执行。
可以看到,当使用了join()之后,程序是等待子线程结束之后才返回到主线程,然后结束进程的