c++ - 将 char* 传递给 pthread_read 函数

标签 c++ linux char pthreads void-pointers

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

我尝试向 pthread_create 中的函数 showMessage 发送一个 char*,但是当我尝试打印它时,屏幕上出现空白区域:

#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

上面一行启动了打印指针指向的字符的线程。此线程在 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++ - 将 char* 传递给 pthread_read 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53135574/

相关文章:

c++ - 有没有办法使用 boost::program_options::parse_config_file 在 INI 文件中包含多个 "name=value"行?

java - crontab 在 linux 上运行 java shell 脚本

linux - WordPress 无法安装主题

linux - 没有任何身份验证的 SSH session

将字符转换为整数

我们可以将格式说明符字符串的地址传递给 printf

带有 char 数组的 C++ 内存池

C++ 在模板类中重载 operator+

c++ - 所有类型的零值?

Android NDK - 在 Visual Studio 中添加更多目标 API 级别