任何人都可以提供一个命令示例来编译使用mingw的mutex和线程的应用程序。
当我尝试使用命令i686-w64-mingw32-g++ -std=c++11 -lpthread -o myprog.exe myprog.cpp
执行此操作时,出现错误,即未声明互斥锁main.cpp:15:1: error: ‘mutex’ does not name a type
以下是代码:
#include <iostream>
#include <thread>
#include <vector>
#include <future>
#include <mutex>
#include <ctime>
#include <cstring>
using namespace std;
#define MAX_SIZE_OF_THE_WORD 15
int nCount = 0;
mutex Mutex;
char * MakeWord(){
srand (time(NULL));
int Size = rand() % MAX_SIZE_OF_THE_WORD;
char Array[Size];
for (auto &w : Array){
srand (time(NULL));
w = (char)(rand()%50);
}
return Array;
}
bool HelloWorldShow(char * YOUR_TEXT){
lock_guard<mutex> M(Mutex);
cout<<"Hello World number --- "<< nCount <<" And here is your text --- "<<YOUR_TEXT<<endl;
nCount++;
if (strlen(YOUR_TEXT) > 3) {
return true;
}
else{
throw runtime_error(false);
}
}
int main() {
int nNum;
cout<<"Enter number of threads"<<endl;
cin>>nNum;
if (nNum >= 50){
cout<< "Restart program and open less than 50 threads"<<endl;
return 0;
}
vector<future<bool>> a_Futures;
const char * Words[nNum];
for (auto &w : Words){
w = MakeWord();
}
for(int i =0; i< nNum; i++){
a_Futures.push_back(async(launch::async, &HelloWorldShow, (char *)Words[i]));
}
try {
for(auto &f : a_Futures) {
bool nRes = f.get();
}
}
catch (exception & ex) {
cout<<"Exiting..."<<endl;
}
return 0;
}
所以...这里是使用@Smeeheey提供的库的代码
#undef _GLIBCXX_HAS_GTHREADS
#include <iostream>
#include "mingw.thread.h"
#include <mutex>
#include "mingw.mutex.h"
#include "mingw.condition_variable.h"
#include <vector>
#include <future>
#include <ctime>
#include <cstring>
using namespace std;
#define MAX_SIZE_OF_THE_WORD 15
int nCount = 0;
mutex Mutex;
char * MakeWord(){
srand (time(NULL));
int Size = rand() % MAX_SIZE_OF_THE_WORD;
char Array[Size];
for (auto &w : Array){
srand (time(NULL));
w = (char)(rand()%50);
}
return Array;
}
bool HelloWorldShow(char * YOUR_TEXT){
lock_guard<mutex> M(Mutex);
cout<<"Hello World number --- "<< nCount <<" And here is your text --- "<<YOUR_TEXT<<endl;
nCount++;
if (strlen(YOUR_TEXT) > 3) {
return true;
}
else{
throw runtime_error(false);
}
}
int main() {
int nNum;
cout<<"Enter number of threads"<<endl;
cin>>nNum;
if (nNum >= 50){
cout<< "Restart program and open less than 50 threads"<<endl;
return 0;
}
vector<future<bool>> a_Futures;
const char * Words[nNum];
for (auto &w : Words){
w = MakeWord();
}
for(int i =0; i< nNum; i++){
a_Futures.push_back(async(launch::async, &HelloWorldShow, (char *)Words[i]));
}
try {
for(auto &f : a_Futures) {
bool nRes = f.get();
}
}
catch (exception & ex) {
cout<<"Exiting..."<<endl;
}
return 0;
}
但我仍然有错误,但这次是错误:'class std :: future'的声明
答案 0 :(得分:2)
你需要
确保源文件中的#include <mutex>
在源文件的顶部使用std::mutex
或using namespace std
。
编辑(看过代码):似乎mingw32本身仍然不支持C ++ 11线程。您可以切换到mingw64,也可以使用this library,这会添加std线程支持。