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

标签 c++ multithreading pthreads

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

#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/

相关文章:

c++ - 派生类和基类之间指针到指针的转换?

c# - 这是线程安全的吧?

c# - 多线程环境下 SendOrPostCallback 和 Action 的区别?

c# - 为什么我的代码不能正常同步工作?

c++ - 线程上下文切换

multithreading - 使克隆的线程 pthread 兼容

c - 多线程程序中的意外输出

c++ - 如何判断Windows是否安装了C/C++编译器?

c++ - main() 之前的段错误

c# - Xamarin 和 C++ 代码