0

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.

Edited by osiron: Typo

3
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by L7Sqr
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.