简体   繁体   English

我的线程程序有什么问题?

[英]What is wrong with my thread program?

I have the following code that is supposed to process ever wile with a .NEF extension. 我有以下代码,应该使用.NEF扩展名来处理。

#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);
}

There is just one file with .NEF extension in the directory. 目录中只有一个带.NEF扩展名的文件。 My expected output is - 我的预期产量是 -

F :DSC_0838.NEF 
W :DSC_0838.NEF

However, I get 但是,我明白了

F :DSC_0838.NEF 
W :RGBbmp.bmp

RGBbmp.bmp is another file in the same directory. RGBbmp.bmp是同一目录中的另一个文件。 What is wrong with my code? 我的代码出了什么问题? Why does it not work as expected? 为什么它不能按预期工作?

The above code was compiled using - 上面的代码使用 - 编译

g++ tmp.cpp -pthread --std=c++11

fn1's address is shared between the main thread and the secondary p_thread you create. fn1的地址在主线程和您创建的辅助p_thread之间共享。 While the new thread is bootstrapping, the main thread changes the value in 'fn1' memory address, and the secondary thread reads the name of a different file (because in the main thread fn1 now has a new value). 当新线程进行自举时,主线程会更改'fn1'内存地址中的值,而辅助线程会读取不同文件的名称(因为在主线程fn1中现在有一个新值)。

You need to create a copy of the string you pass to the secondary thread, or you need to syncrhonize your read/write, I would recommend the former since it is way easier. 你需要创建一个传递给辅助线程的字符串的副本,或者你需要同步你的读/写,我会推荐前者,因为它更容易。

In this line: if (rc=pthread_create( &t1, NULL, &workHorse, (void*)&fn1)) 在这一行:if(rc = pthread_create(&t1,NULL,&workHorse,(void *)&fn1))

You are passing the address of fn1, the value then is changed in the main loop to some other file names, and by the time the tread comes up, it is now in RGBbmp.bmp 您正在传递fn1的地址,然后在主循环中将值更改为其他一些文件名,并且当胎面出现时,它现在位于RGBbmp.bmp中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM