Giving name to a thread

Hey everyone, I'm trying to give a thread name to my threads every time it generates. The problem I face now is that I dunno how.
I make an array called threadNames.

I've tried to implement the threadNames to the create part but failed terribadly, any one can show me the way hahaha thx!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
int threadGen() {

    string threadNames[]={"THREAD A", "THREAD B", "THREAD C", "THREAD D"};

    pthread_t thread1, thread2;
    string thread_Msg1 = "A new Thread has been created!!!";
    string * thread_message1 = &thread_Msg1;
    string thread_Msg2 = "A new Thread has been created!!!";
    string * thread_message2 = &thread_Msg2;

    //create new thread
    if (pthread_create(&thread1, NULL, mSolve, thread_message1) != 0) {
        return EXIT_FAILURE;
    } else {
        cout << thread_Msg1 << endl;
    }
	
    //create new thread
    if (pthread_create(&thread2, NULL, mSolve, thread_message2) != 0) {
        return EXIT_FAILURE;
    } else {
        cout << thread_Msg2 << endl;
    }

    if (pthread_join(thread1, NULL) != 0) {
        return EXIT_FAILURE;
    }

    if (pthread_join(thread2, NULL) != 0) {
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}
EDIT : it has belatedly sunk in that you are waiting for the threads to exit.

But I would probably still avoid passing the address of a local variable to a thread.

What do you mean by "failed terribadly" ?? (as in, what happened?)

And I would be careful with your returns. What happens if the first thread succeeds but the second doesn't.

Andy

Original attempt...

thread_message1 and thread_message2 are pointing at local variables.

1
2
    string thread_Msg1 = "A new Thread has been created!!!"; // LOCAL variable!
    string * thread_message1 = &thread_Msg1;


So, if the thread continues to run after threadGen() exits, it will be ttempting to use a variable that no longer exists.

Use new instead (e.g.)

1
2
    const char thread_Msg1[] = "A new Thread has been created!!!"; // LOCAL variable!
    string * thread_message1 = new string(thread_Msg1);


Note that, before it exits, the thread should delete the string you passed it.
Last edited on
Hey thx for the info, in other words can I create multiple names using these method?
You can pass whatever strings (or other data) you want to your threads, as long as you take care of the variables' lifetimes.

Did your app crash?

(Actually -- following on from TheCreator's following message -- what do you want to use the names for?)
Last edited on
you dont needs names
you can reference them through their PID
Topic archived. No new replies allowed.