沒有引數的簡單執行緒

這個基本示例在我們命名為 sync(main) 和 async(new thread)的兩個執行緒上以不同的速率計數。主執行緒以 1Hz(1s) 計數到 15,而第二個以 0.5Hz(2s) 計數到 10。因為主執行緒更早完成,我們使用 pthread_join 使其等待非同步完成。

#include <pthread.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>

/* This is the function that will run in the new thread. */
void * async_counter(void * pv_unused) {
    int j = 0;
    while (j < 10) {
        printf("async_counter: %d\n", j);
        sleep(2);
        j++;
    }

    return NULL;
}

int main(void) {
    pthread_t async_counter_t;
    int i;
    /* Create the new thread with the default flags and without passing
     * any data to the function. */
    if (0 != (errno = pthread_create(&async_counter_t, NULL, async_counter, NULL))) {
        perror("pthread_create() failed");
        return EXIT_FAILURE;
    }

    i = 0;
    while (i < 15) {
        printf("sync_counter: %d\n", i);
        sleep(1);
        i++;
    }

    printf("Waiting for async counter to finish ...\n");

    if (0 != (errno = pthread_join(async_counter_t, NULL))) {
        perror("pthread_join() failed");
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

複製自此處: http//stackoverflow.com/documentation/c/3873/posix-threads/13405/simple-thread-without-arguments ,最初由 M. Rubio-Roy 建立。