Domanda

I am reading an input line by line from stdin. I am sending each line to a threaded function. But I can see only output of the first input. How can I see output of each input? Here is the code

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

Here is the output I get :

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

The input is:

hello1
hello2
hello3
hello4
hello5
hello6
hello7
hello8
hello9
hello10

I want to get:

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
È stato utile?

Soluzione 2

Change const char *arrays[10]; to string arrays[10];
and arrays[k] = line.c_str(); to arrays[k] = line;
and (void*) arrays[k] to (void*)arrays[k].c_str().

The problem is that once the line changes to the next value previous arrays[k] points to a meaningless piece of memory. You have to save the value of line in order to enable the thread to access it.

Altri suggerimenti

arrays[k] = line.c_str(); This is not doing what you think it does... and since this is what you give to your print_message functions...

The result of std::string::c_str() is only guaranteedly available as the std::string does not change and does not get destructed (when you do a new getline you invalidated the result of the previous c_str(). If you cant to keep the const char* for more time than that, you will need to take a copy. Like:

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);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top