【发布时间】:2016-06-01 10:06:01
【问题描述】:
任何人都可以提供一个命令示例来编译一个使用互斥锁和线程的应用程序。
当我尝试使用命令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'的声明
【问题讨论】:
标签: c++ multithreading mingw mingw32 mingw-w64