August 17, 2015

Multiple Threads using C



In the paragraph, we would like to talk about multiple thread and I will do a little example code in C.

Source Code : 


#include 
#include 
 
void* thread0(void*);
void* thread1(void*);
 
int main(void)
{
    void* result;
    pthread_t t0; 
    pthread_t t1; 

    pthread_create(&t0, NULL, thread0, NULL);
    pthread_create(&t1, NULL, thread1, NULL);

    /* wait for thread terminate */
    pthread_join(t0, &result);
    pthread_join(t1, &result);

    return 0;
}
 
void* thread0(void *argu) 
{
    int i = 0;

    for (i = 0; i < 10; i++) 
    {
        printf("thread0: %d\n", i); 
        sleep(1);
    }   

    return 0;
}
 
 
void* thread1(void *argu) 
{
    int i = 0;

    for (i = 0; i < 10; i++) 
    {
        printf("thread1: %d\n", i); 
        sleep(1);
    }   
    return 0;
}

Compile and Run : 

  1. Windows : Just directly press F5
  2. Linux : Ubuntu 14.04
  3. gcc -o mthread mthread.c -l pthread
    ./mthread
  4. Notice : Don;t forget to add pthread to compile

Result :

Multi-thread :

Single thread :



No comments :

Post a Comment