pthread

Process is a running program and in multi task OS, different process is allocated to each memory space. Basically, memory space can not be accessed from different process.

Thread is an executable unit which is executed independently in one process. And Each thread has same memory space. Generally, a process, which called main thread, is booted and run program which is written within main().

#include <stdio.h>
#include <unistd.h>  // define sleep()
#include <pthread.h>

// thread
void* thread( void* args )
{	
    int counter = 0;
    while( 1 ){
        printf( "thread : %d\n", counter );
        sleep( 1 ); // thread is stopped for one second
        counter++;
    }

    return NULL;
}

// main thread
int main() 
{
    pthread_t th;

    // create thread and run
    pthread_create( &th, NULL, thread, (void *)NULL );

    // wait until it get any key
    getchar();

    return 0;
}


eg2
When user type any key, program is finished in previous example. pthread_join() waits until thread is finished.

#include <stdio.h>                                                              
#include <unistd.h>  // define thread
#include <pthread.h>

int counter = 0;

// thread
void* thread( void* args )
{
    int i = 0;
    for( i = 0; i < 10; ++i , ++counter ){
        printf( "thread : %d\n", counter );
        sleep( 1 ); // thread is stopped one sec
    }   

    return NULL;
}

// main thread
int main()
{
    pthread_t th; 

    // creaste thread and run
    pthread_create( &th, NULL, thread, (void *)NULL );
    scanf( "%d", &counter );

    // wait until thread is finished
    pthread_join( th, NULL );

    return 0;
}
Remove all ads