gpt4 book ai didi

c++ - 多线程无法按预期工作

转载 作者:行者123 更新时间:2023-11-27 23:06:27 25 4
gpt4 key购买 nike

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

#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

最佳答案

数组[k] = line.c_str();这并没有按照您的想法行事...因为这是您为 print_message 函数提供的内容...

关于c++ - 多线程无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23243742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com