我正在從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
你覺得會發生什麼事line'的'值與通過裝載機循環每次迭代你怎麼想它的影響範圍內'保存的數據? line的內部緩衝區(你知道,每次迭代都是聖人嗎?)在啓動線程之前,在你的指針數組中打印地址(所有這些),你可能會發現它。 – WhozCraig
如果可能,我強烈建議使用C++ 11中的線程API。 – Jarod42