Search code examples
c++multithreadingpointerspthreadssleep

Thread ending unexpectedly. c++


I'm trying to get a hold on pthreads. I see some people also have unexpected pthread behavior, but none of the questions seemed to be answered.

The following piece of code should create two threads, one which relies on the other. I read that each thread will create variables within their stack (can't be shared between threads) and using a global pointer is a way to have threads share a value. One thread should print it's current iteration, while another thread sleeps for 10 seconds. Ultimately one would expect 10 iterations. Using break points, it seems the script just dies at

while (*pointham != "cheese"){

It could also be I'm not properly utilizing code blocks debug functionality. Any pointers (har har har) would be helpful.

#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>
#include <string>

using namespace std;
string hamburger = "null";
string * pointham = &hamburger;

void *wait(void *)
{
    int i {0};
    while (*pointham != "cheese"){
        sleep (1);
        i++;
        cout << "Waiting on that cheese " << i;
    }
    pthread_exit(NULL);
}

void *cheese(void *)
{
    cout << "Bout to sleep then get that cheese";
    sleep (10);
    *pointham = "cheese";
    pthread_exit(NULL);
}

int main()
{

   pthread_t threads[2];
   pthread_create(&threads[0], NULL, cheese, NULL);
   pthread_create(&threads[1], NULL, wait, NULL);

   return 0;
}

Solution

  • The problem is that you start your threads, then exit the process (thereby killing your threads). You have to wait for your threads to exit, preferably with the pthread_join function.