C ++ pthread_create不会在函数中打印

时间:2018-02-18 12:34:27

标签: c++ linux multithreading pthreads

我有这个程序,当用户输入“run”时会运行一个线程
问题是

printf("\n%s", message); //will not be printed out

如果取消注释printMsg()中的for循环,输出就像这样

Hello World COUNTER: 0
Hello World COUNTER: 1

但我期待像

这样的东西
Hello World COUNTER: 0
Hello World COUNTER: 1
Hello World COUNTER: 2

我错过了正确运行pthread的内容吗?
代码:

#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <readline/readline.h>
#include <pthread.h>

using namespace std;

struct ThreadStruct
{
    const char *filename;
    int noOfRepeat;
    int interval;
};

void *printMsg( void *ptr )
{
    struct ThreadStruct *args = (struct ThreadStruct *)ptr;
    const char *message = args->filename;
    int noOfRepeat = args->noOfRepeat;
    int interval = args->interval;

    printf("\n%s", message);

    /*
    for(int i=0; i<noOfRepeat; i++){
         printf("\n%s COUNTER: %d", message, i);
         sleep(interval);
    }
    */
}


int main()
{

    char* input = NULL;

    do {
        //get input from user
        input = readline("Input: ");

        //check if input is run
        if(strcmp(input, "run") == 0){

            //create a thread to run print_message_function
            struct ThreadStruct *myStruct;
            myStruct = (ThreadStruct *) malloc(sizeof(ThreadStruct));
            myStruct->filename = "Hello World";
            myStruct->noOfRepeat = 3;
            myStruct->interval = 3;

            pthread_t thread;
            pthread_create( &thread, NULL, printMsg, (void*) myStruct);
        }
    } while(strcmp(input, "exit") != 0);

    return 0;
}

仅供参考,我用它来编译

g++ main.cpp -lreadline -lpthread -o main

0 个答案:

没有答案