繁体   English   中英

多线程无法按预期工作

[英]Multithreading doesn't work as expected

我正在从stdin逐行读取输入。 我将每一行发送到一个线程函数。 但是我只能看到第一个输入的输出。 如何查看每个输入的输出? 这是代码

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string>
#include <string.h>
#include <iostream>
#include <unistd.h>

using namespace std;

pthread_mutex_t lock;
void *print_message_function( void *ptr );

main()
{
    pthread_t mythread[10];
    const char *arrays[10];
    int irets[10];

    string line;
    int k = 0;

    while(getline(cin,line))
    {

        if(!line.empty())
        {
            arrays[k] = line.c_str();

            irets[k] = pthread_create( &mythread[k], NULL, print_message_function, (void*) arrays[k]);
            usleep(100);
            k++;
        }
    }

    for(int i = 0; i < 10; i++)
    {
        pthread_join( mythread[i], NULL);
    }


    pthread_mutex_destroy(&lock);


    exit(0);
}

void *print_message_function( void *ptr )
{    

    pthread_mutex_lock(&lock);

    char *message;
    message = (char *) ptr;

    printf("first %s \n", message);
    sleep(1);
    printf("second %s \n", message);
    pthread_mutex_unlock(&lock);
}

这是我得到的输出:

first hello1
second  
first  
second  
first  
second  
first  
second  
first  
second  
first  
second  
first  
second  
first  
second  
first  
second  
first  
second  

输入为:

hello1
hello2
hello3
hello4
hello5
hello6
hello7
hello8
hello9
hello10

我想得到:

first hello1
second hello1  
first  hello2
second  hello2
first  hello3
second  hello3
first  hello4
second  hello4
first  hello5
second  hello5
first  hello6
second  hello6
first  hello7
second  hello7
first  hello8
second  hello8
first  hello9
second  hello9
first  hello10
second  hello10

arrays[k] = line.c_str(); 这并没有按照您认为的那样做...并且由于这是您给print_message函数提供的...

更改const char *arrays[10]; string arrays[10];
arrays[k] = line.c_str(); arrays[k] = line;
(void*) arrays[k](void*)arrays[k].c_str()

问题是,一旦该line更改为下一个值,则先前的arrays[k]指向无意义的内存。 您必须保存line的值才能使线程访问它。

std::string::c_str()的结果仅能保证可用,因为std::string不会改变且不会被破坏(当您执行新的getline时,会使先前c_str()的结果无效。无法将const char*保存更长的时间,您将需要复制一个副本,例如:

arrays[k] = malloc(line.size()+1); //Plus 1 because of the \0 on the end of the string
memcpy(arrays[k],line.c_str(),line.size()+1);

暂无
暂无

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

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