2014-04-23 250 views
0

我正在從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 
+0

你覺得會發生什麼事line'的'值與通過裝載機循環每次迭代你怎麼想它的影響範圍內'保存的數據? line的內部緩衝區(你知道,每次迭代都是聖人嗎?)在啓動線程之前,在你的指針數組中打印地址(所有這些),你可能會發現它。 – WhozCraig

+0

如果可能,我強烈建議使用C++ 11中的線程API。 – Jarod42

回答

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

arrays[k] = line.c_str(); 這不是做你認爲它...而且由於這是你給你的print_message功能...

+0

是的,你必須memcopy數據或者創建一個std :: strings數組。因爲當修改'input''input.c_str()'確實也改變了。 – Theolodis

1

std::string::c_str()的結果只有guaranteedly可作爲std::string不會改變,不會被破壞(當你做你無效以前c_str()的結果,一個新的函數getline。如果你不能保持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); 
+0

當我們有更好的類似C++的方式時,爲什麼要回到類C方法呢? – Dialecticus

+0

@Dialecticus關於這個問題的教學目的。瞭解什麼是錯誤的以避免將來的錯誤是非常有價值的。我當然更喜歡C++方法。 –