Creative Commons License Foxbond's Repo

/** (c) 2012 Michał (Foxbond) Chraniuk */
#include <pthread.h>
#include <iostream>
#include <string>
#include <stdio.h>
#include <time.h>

void* print_message_function(void *doPrint) {
    bool* vDoPrint = (bool*) doPrint;
    while (*vDoPrint) {
        _sleep(500);
        std::cout << "Thread 1" << std::endl;
    }
    return NULL;
}

void* keyPressed(void* doPrint) {
    bool* vDoPrint = (bool*) doPrint;
    while (*vDoPrint) {
        *vDoPrint = (char) getchar() == 'k' ? false : true;
        std::cout << "THIS ISN'T DISPLAYED UNLESS 'k' PRESSED.";
    }
    return NULL;
}

int main(int argc, char* argv[]) {
    pthread_t thread1, thread2;
    int iret1, iret2;
    bool doPrint = true;
    iret2 = pthread_create(&thread2, NULL, print_message_function,
            (void*) &doPrint);
    iret1 = pthread_create(&thread1, NULL, keyPressed,
            (void*) &doPrint);

    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);

    std::cout << "Thread 1 returns: " << iret1 << std::endl;
    std::cout << "Thread 2 returns: " << iret2 << std::endl;
    return 0;
}

> Back