//test.cpp
#include <stdio.h>
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mMutex;
using namespace std;
static int count=0;
static int MAX=5000;
static int line=0;
static int line_count=5;
void thread1(){
while(1){
if(count <MAX ){
mMutex.lock();
if(count <MAX ){
std::cout<<"A: "<<++count<<" ";
if(++line == line_count){
std::cout<<endl;
line = 0;
}
}else{
break;
}
mMutex.unlock();
}
}
}
void thread2(){
while(1){
if(count <MAX ){
mMutex.lock();
if(count <MAX ){
std::cout<<"B: "<<++count<<" ";
if(++line == line_count){
std::cout<<endl;
line = 0;
}
}else{
break;
}
mMutex.unlock();
}
}
}
int main()
{
std::thread mThread1(thread1);
std::thread mThread2(thread2);
mThread1.detach();
mThread2.detach();
while(1){
int x;
std::cin>>x;
if(x==0){
break;
}
}
return 0;
}在终端中执行:
g++ -std=c++11 test.cpp -pthread -o test.out
编译报错:
terminate called after throwing an instance of 'std::system_error'
what(): Enable multithreading to use std::thread: Operation not permitted
在网上查阅资料测试加上-Wl,--no-as-needed 就能正常编译运行了,完整的执行指令为:
g++ -std=c++11 -Wl,--no-as-needed test.cpp -pthread -o test.out
版权声明:本文为DFLee原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。