C++ 我的线程程序有什么问题?
我有下面的代码,应该用.NEF扩展名处理ever-wileC++ 我的线程程序有什么问题?,c++,pthreads,C++,Pthreads,我有下面的代码,应该用.NEF扩展名处理ever-wile #include <iostream> #include <regex> #include <pthread.h> #include <dirent.h> using namespace std; void *workHorse(void*); int main (int argc, char *argv[]){ pthread_t t1; int rc, pos1;
#include <iostream>
#include <regex>
#include <pthread.h>
#include <dirent.h>
using namespace std;
void *workHorse(void*);
int main (int argc, char *argv[]){
pthread_t t1;
int rc, pos1;
DIR *dir;
struct dirent *ent;
regex e("(.*)(\\.)(NEF|nef)");
if ((dir = opendir (".")) != NULL) {
string fn1;
while ((ent = readdir (dir))!=NULL){
fn1.assign(ent->d_name);
if (regex_match ( fn1, e )){
cout<<"F :"<<fn1.c_str()<<" "<<endl;
if (rc=pthread_create( &t1, NULL, &workHorse, (void*)&fn1)){
cout<<"Error creating threads "<<rc<<endl;
exit(-1);
}
}
}
}
return 0;
}
void *workHorse(void *fileName){
int ret;
cout<<"W :"<<((string*)fileName)->c_str()<<endl;
pthread_exit(NULL);
}
然而,我明白了
F :DSC_0838.NEF
W :RGBbmp.bmp
RGBbmp.bmp
是同一目录中的另一个文件。我的代码有什么问题?为什么它不能像预期的那样工作
上面的代码是使用-
g++ tmp.cpp -pthread --std=c++11
fn1的地址在主线程和您创建的辅助p_线程之间共享。 当新线程正在引导时,主线程更改“fn1”内存地址中的值,次线程读取不同文件的名称(因为在主线程中fn1现在有一个新值) 您需要创建传递给次线程的字符串的副本,或者需要同步读/写操作,我建议使用前者,因为前者更容易 在这方面: if(rc=pthread_create(&t1,NULL,&workHorse,(void*)&fn1))
您正在传递fn1的地址,然后该值在主循环中被更改为其他一些文件名,当出现踏板时,它现在位于RGBbmp.bmp中,只有一个
fn1
string对象,其中传递了指向该对象的指针。但是,主线程中的cout
会立即评估它的副作用。您还使用多个线程来打印cout,这不是线程安全的。您的输出可能会严重混乱和混杂。谢谢。这是我的第一个线程程序,我从来没有想过线程安全。
g++ tmp.cpp -pthread --std=c++11