user1578897
user1578897

Reputation: 179

C++ - Pthread how to send in value

How do I send in a std::string into my thread?

This is my code:

void* sendReminder(void*) 
{
    system("echo 'hello' >> buffer.txt");    
}

int main()
{
    string str1 = "somevalue";
    pthread_t t1;
    pthread_create(&t1, NULL, &sendReminder, NULL);
}

Upvotes: 2

Views: 2744

Answers (2)

pb2q
pb2q

Reputation: 59607

Use the fourth argument to pthread_create to send an "argument" to your function, just be sure to make a copy of it on the heap:

string *userData = new string("somevalue");    
pthread_create(&t1, NULL, &sendReminder, (void *) userData);

If you'll be using pthread_join to wait on the new thread(s), suspending execution of the caller, you can get away with just passing an address of the local variable:

if (pthread_create(&t1, NULL, &sendReminder, (void *) &str1) == 0)
{
    pthread_join(t1, &result);
    // ...

You can retrieve the value with:

void* sendReminder(void* data) 
{
    std::string* userData = reinterpret_cast<std::string*>(data);
    // Think about wrapping `userData` within a smart pointer.

    cout << *userData << endl;
}

Upvotes: 5

mathematician1975
mathematician1975

Reputation: 21351

You pass the value in as a void* in the last argument to pthread_create. Inside the thread function, you cast the void* back to the type of the object that you passed in. In this case a string.

Upvotes: 2

Related Questions