欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > c/c++ >内容正文

c/c++

g++编译c++11 thread报错问题 及c++多线程操作

发布时间:2025/3/15 c/c++ 44 豆豆
生活随笔 收集整理的这篇文章主要介绍了 g++编译c++11 thread报错问题 及c++多线程操作 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

测试代码thread.cpp

#include <thread> #include <iostream> using namespace std;void run(int n){for(int i = 0; i < 5; i++) {cout << "thread " << n << endl;} } int main() {cout << "hahahha" << endl;thread t1(run, 1);thread t2(run, 2);t1.join();t2.join();return 0; }

直接g++编译一下
g++ thread.cpp -o mythread
会发现报错

In file included from /usr/include/c++/5/thread:35:0,from thread.cpp:1: /usr/include/c++/5/bits/c++0x_warning.h:32:2: error: #error This file requires compiler and library support for the ISO C++ 2011 standard. This support must be enabled with the -std=c++11 or -std=gnu++11 compiler options.#error This file requires compiler and library support \

解决方法是g++参数添加“-std=c++11”,但接着编译时,又会报另一个问题

$ g++ thread.cpp -std=c++11 -o mythread /tmp/ccbLvKA8.o: In function `std::thread::thread<void (&)(int), int>(void (&)(int), int&&)': thread.cpp:(.text._ZNSt6threadC2IRFviEJiEEEOT_DpOT0_[_ZNSt6threadC5IRFviEJiEEEOT_DpOT0_]+0x93): undefined reference to `pthread_create' collect2: error: ld returned 1 exit status

解决办法是编译参数添加“-lpthread”

$ g++ thread.cpp -std=c++11 -o mythread -lpthead /usr/bin/ld: cannot find -lpthead collect2: error: ld returned 1 exit status $ g++ thread.cpp -std=c++11 -o mythread -lpthread $ ./mythread hahahha thread1 thread1 threadthread2 thread2 thread2 thread2 thread2 1 thread1 thread1

因为cout打印不是原子操作,会导致thread1和thread2混着打印
先试着使用mutex加锁,更改一下代码

#include <thread> #include <iostream> #include <mutex>using namespace std;mutex mLock;void run(int n){for(int i = 0; i < 5; i++) {mLock.lock();cout << "thread" << n << endl;mLock.unlock();} }int main() {cout << "hahahha" << endl;thread t1(run, 1);thread t2(run, 2);t1.join();t2.join();return 0; }

运行结果:
$ ./mythread
hahahha
thread1
thread1
thread1
thread1
thread1
thread2
thread2
thread2
thread2
thread2

因为在run函数中有可能会发现异常,导致unlock没有执行到,进程可能会挂死
解决办法是使用lock_guard,由lock_guard控制构造和析构流程,会自动unlock,运行结果是一样的。

void run(int n){for(int i = 0; i < 5; i++) {//mLock.lock();lock_guard <mutex> guard(mLock);cout << "thread" << n << endl;//mLock.unlock();} }

也可以利用unique_lock,这个功能和lock_guard类似,但提供的功能更多些,try_to_lock尝试去lock,可通过owns_lock判断是否持锁成功

void run(int n){for(int i = 0; i < 5; i++) {//mLock.lock();//lock_guard <mutex> guard(mLock);unique_lock <mutex> lock(mLock, try_to_lock);//try to lockcout << "thread" << n << ", lock result:" << lock.owns_lock() << endl;//mLock.unlock();} }

运行结果,偶尔能看到没有持到锁的情况。
$ ./mythread
hahahha
thread1, lock result:1
thread1, lock result:1
thread1, lock result:1
thread1, lock result:1
thread1, lock result:1
thread2, lock result:0
thread2, lock result:1
thread2, lock result:1
thread2, lock result:1
thread2, lock result:1

总结

以上是生活随笔为你收集整理的g++编译c++11 thread报错问题 及c++多线程操作的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。