Hi guys,

I'm kinda new to pthreading and so I made this program that prints "hello" 10 times but I wanted to have a delay where it puts "hello" in one second between time interval (like a stopwatch). Unfortunately, I used the sleep(1) function and it only prints out one "hello" then the program exits.

Output:
hello

Expected output:
hello
// one second later
hello
// one second later
8 hellos later with one second in between

Here is the following code I've been testing on:

#include <iostream>
#include <pthread.h>
#include <unistd.h>
using namespace std;

void *print(void *arg){
    bool ticking = true;
    int i = 0;
    char *s = (char *) arg;
    pthread_detach(pthread_self());
    while(ticking && i < 10){
        cout << s << endl;
        sleep(1); //one second stop
        i++;
    }
    return 0;
}

int main(){
    pthread_t tid;
    pthread_create(&tid, 0, print, (void *) "hello");
    return 0;
}

Any help would be appriciated. Thanks.

The program exits because main() did not wait for the thread to complete its task. You need to create a mutex then call pthread_cond_wait()

You may also want to look into pthread_join

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.