Pthread Example

說真的,我不喜歡寫 Multi-thread 的程式,因為討厭處理 thread 之間的同步問題(我這個人就是怕麻煩!)但怕以後可能會用到,所以還是留下一些範例程式以後可以參考。所有範例程式都是從網路上找來再加上一些修改後放上。

總共有兩個範例,第一個範例是單純的使用 multi-thread 的功能,可以比較 multi-thread 和 single-thread 的效率差異。程式碼如下:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

/* A task that takes some time to complete. The id identifies distinct
   tasks for printed messages. */

void *task(int id) 
{
    int i;
    double result = 0.0;

    printf("Task %d started\n", id);
      
    for (i = 0; i < 9000000; i++) 
    {
        result = result + sin(i) * tan(i);
    }
    
    printf("Task %d completed with result %e\n", id, result);
}

/* Same as 'task', but meant to be called from different threads. */
void *threaded_task(void *t) 
{
    long id = (long) t;
    printf("Thread %ld started\n", id);
    task(id);
    printf("Thread %ld done\n", id);
    pthread_exit(0);
}

/* Run 'task' num_tasks times serially. */
void *serial(int num_tasks) 
{
    int i;
    
    for (i = 0; i < num_tasks; i++) 
    {
        task(i);
    }
}

/* Run 'task' num_tasks times, creating a separate thread for each
   call to 'task'. */
void *parallel(int num_tasks)
{
    int num_threads = num_tasks;
    pthread_t thread[num_threads];
    int rc;
    long t;
  
    for ( t = 0; t < num_threads; t++ ) 
    {
        printf("Creating thread %ld\n", t);
        rc = pthread_create( &thread[t], NULL, threaded_task, (void *)t );
      
        if (rc) 
        {
            printf( "ERROR: return code from pthread_create() is %d\n", rc );
            exit(-1);
        }
    }
}

void *print_usage(int argc, char *argv[]) 
{
    printf("Usage: %s serial|parallel num_tasks\n", argv[0]);
    exit(1);
}

int main( int argc, char *argv[] ) 
{
    if (argc != 3) 
    {
        print_usage( argc, argv );
    }

    int num_tasks = atoi( argv[2] );

    if ( !strcmp( argv[1], "serial" ) ) 
    {
        serial( num_tasks );
    } 
    else if (!strcmp( argv[1], "parallel" ) ) 
    {
        parallel( num_tasks );
    }
    else 
    {
        print_usage( argc, argv );
    }

    printf("Main completed\n");
    pthread_exit(NULL);
    
    return 0;
}


第二個範例是使用 Mutex 的範例。程式碼如下:

#include <sys/time.h>
#include <stdio.h>
#include <pthread.h> 
#include <errno.h>

pthread_mutex_t region_mutex = PTHREAD_MUTEX_INITIALIZER;

int b;  /* buffer size = 1; */

void *producer();
void *consumer();
 
int main()  
{
    pthread_t producer_thread; 
    pthread_t consumer_thread; 
  
    pthread_create( &producer_thread, NULL, producer, NULL );
    pthread_create( &consumer_thread, NULL, consumer, NULL );
    
    pthread_join( consumer_thread, NULL );    
//    return 0;
}

void add_buffer()
{
    b++;
}

void del_buffer()
{
    b--;
}

int get_buffer()
{
    return b ;
}
 
void *producer()
{
    while (1) 
    {
        pthread_mutex_lock( &region_mutex );
        printf( "I'm a producer. " );
        add_buffer();
        printf( "Buffer: %d\n", get_buffer() );
        pthread_mutex_unlock( &region_mutex );
    }
    pthread_exit(NULL);
}

void *consumer()
{
    while (1)
    {
        pthread_mutex_lock(&region_mutex);
        printf("I'm a consumer. ");
        del_buffer();
        printf( "Buffer: %d\n", get_buffer() );
        pthread_mutex_unlock(&region_mutex);
    }
    pthread_exit(NULL);
}
要如何確定 multi-thread 是有將 thread 分配到不同的 core 呢?可以使用 ps -eLF這個指令。

留言

這個網誌中的熱門文章

如何將Linux打造成OpenFlow Switch:Openvswitch

我弟家的新居感恩禮拜分享:善頌善禱

Linux Virtual Interface: TUN/TAP