多线程不能按预期工作

时间:2014-04-23 12:06:15

标签: c++ multithreading pthreads

我正在从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

3 个答案:

答案 0 :(得分:2)

arrays[k] = line.c_str(); 这不符合您的想法......因为这是您为print_message函数提供的内容......

答案 1 :(得分:1)

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的值才能使线程能够访问它。

答案 2 :(得分:1)

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