将 char* 传递给 pthread_read 函数

Pass char* to pthread_read function

我正在尝试创建一个 pthread 并将其插入到我在 file.txt 中阅读的每一行的列表中。

我尝试将 char* 发送到 pthread_create 中的函数 showMessage,但是当我尝试打印它时,屏幕上出现空白 space:

#include <iostream>
#include <thread>
#include <list>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pwd.h>

using namespace std;

void *showMessage( void *ptr ){

   cout << "String: " << (char*)ptr << endl; //Blank space

    pthread_exit(0);
}


int main(int argc, char **argv) 
{  
    list<pthread_t*>thrds;
    list<pthread_t*>::iterator it;
    pthread_t * pt;
    size_t len = 0;
    size_t read;
    char * line = NULL;
    FILE * fp;
    int iret;

    fp = fopen ("./file.txt","r");
    if (fp == NULL)
    {
      fclose (fp);
      return 1;
    }

    while ((read = getline(&line, &len, fp)) != -1) {   //Read file.txt
        pt = new pthread_t();
        thrds.push_back(pt);
        iret = pthread_create( pt, NULL, showMessage, line); //Create pthread and send function ShowMessage and line read in file.txt
        if(iret)
        {   
           fprintf(stderr,"Error - pthread_create() return code: %d\n",iret);
           exit(EXIT_FAILURE);
        }
    }

    for (list<pthread_t*>::iterator it = thrds.begin(); it != thrds.end(); ++it){
         pthread_join( **it, NULL);   
    }

    fclose (fp);

    return 0;
}

你的程序有未定义的行为,因为你同时写入和读取同一个内存缓冲区,看:

iret = pthread_create( pt, NULL, showMessage, line); // start reading operation

上面的行启动了打印 line 指针指向的字符的线程。此线程在 while 循环的下一次迭代中启动后,您调用 getline 函数,该函数通过指针获取 linegetline 可能会在启动线程中打印时同时修改 line 指向的字符串。

读取行后,您可以复制一份,然后将此副本传递给打印功能。

    pt = new pthread_t();
    thrds.push_back(pt);
    char* copy = malloc(strlen(line)+1);
    strcpy(copy,line);
    iret = pthread_create( pt, NULL, showMessage, copy); // <-

现在,写入和读取操作是分开的,应该可以了。记得释放所有分配的资源。

由于您使用的是 C++,因此使用 std::threadstd::string 而不是 pthreads 和原始 char*s 会容易得多。 std::thread 不仅更容易与 C++ 对象一起使用,而且它也是跨平台的。

使用标准的 C++ 构造,您的程序将如下所示:

#include <iostream>
#include <thread>
#include <list>
#include <fstream>

void showMessage(const std::string& str) {
   std::cout << "String: " << str << '\n';
}

int main() {  
    std::list<std::thread> thrds;

    std::ifstream file("file.txt");

    std::string line;
    while (std::getline(file, line)) {   //Read file.txt
        thrds.emplace_back(showMessage, std::move(line)); // Create thread and add it to the list
    }

    for (std::thread& th : thrds) {
         th.join();
    }
}

Live Demo