Pthread [closed]

问题描述 投票:1回答:1

Sorry for my English.I'm use QT Creator.I'm just starting to study threads) And this is my first serious problem.I do not understand why I cannot get the exact value of my string from a thread function.

With string

My code

Output

I tried many options, but everything turned out to be in vain.I tried to do 'char *' instead of 'string'... tried to make structure, but still not working.

with struct

#include <iostream>
#include <pthread.h>
#include <string>
#include <cstring>

#define NUM_THREAD 4

using namespace std;

struct message_info {
    char* message;
};

void *PrintMessage(void *arg) {
    message_info *new_info;
    new_info = (struct message_info*)arg;
    pthread_t id = pthread_self();
    cout << "ID thread :" << id << new_info->message << endl;
    pthread_exit(NULL);
}

int main(){
    pthread_t id_stream[NUM_THREAD];
    for (int i = 0; i < NUM_THREAD; i++){
        struct message_info call_mess;
        call_mess.message = "This is messaf";
        int rec = pthread_create(id_stream, NULL, PrintMessage, (void *)&call_mess);
        if (rec != 0) {
            cout << "Error: Thread not created | " << rec << endl;
            exit(-1);
        }
    }
    pthread_exit(NULL);
}
c++ pthreads
1个回答
1
投票
int rec = pthread_create(id_stream, NULL, PrintMessage, (void *)&call_mess)

This creates a new thread, passing to it a pointer to call_mess, as a parameter to PrintMessage.

This, the parent thread, immediately continues running, it returns from pthread_create() and reaches the end of the loop, at which point the call_mess object gets destroyed. call_mess exists only until the end of the for loop, at which point it gets destroyed before the for loop iterates again (or not).

You have absolutely no guarantees whatsoever that the new thread will start running, will read the pointer that it receives as a parameter, and will make a copy of it, before call_mess gets destroyed at the end of the loop in the parent thread. The only guarantee pthread_create gives you is that the new thread will start executing. Some time in some unspecified future, and it may not be even running yet after pthread_create() returns. But it will run. Some day. Some time. Eventually.

So what's obviously happening here is that this call_mess object is getting destroyed before each new thread reads it. That's it. Welcome to the world of multiple execution threads. This results in undefined behavior, and random garbage results that you see.

In order to do this correctly you will have to write more code, employing mutexes and condition variables, to make the parent thread wait until the new thread starts executing and fetches its parameters, and have the parent thread resume execution only after the child thread fetched out its parameters.

© www.soinside.com 2019 - 2024. All rights reserved.