POSIX Threads Simple Thread without Arguments


This basic example counts at different rates on two threads that we name sync (main) and async (new thread). The main thread counts to 15 at 1Hz (1s) while the second counts to 10 at 0.5Hz (2s). Because the main thread finishes earlier, we use pthread_join to make it wait async to finish.

#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);

    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);

    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;

Copied from here: http://stackoverflow.com/documentation/c/3873/posix-threads/13405/simple-thread-without-arguments where it had initially been created by M. Rubio-Roy.