1. 程式人生 > >Linux系統下C語言執行緒

Linux系統下C語言執行緒

先上程式碼

/*
 * gcc multiple_thread.c -lpthread -o multiple_thread
*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

#define length 10

void thread1(void) {
    int i;
    for(i=0; i<10; i++) {
       printf("thread .. 1\n");
       usleep(200000);
    }
}

void thread2(void) {
    int i;
    for(i=0; i<10; i++) {
       printf("thread .... 2\n");
       usleep(200000);
    }
}

void thread3(void* p) {
    char *c=(char *)p;
    for(int i=0; i<length; i++) {
       printf("%s\n", c);
       usleep(200000);
    }
}

int main(void) {

    pthread_t pt1, pt2, pt3;
    int ret1, ret2, ret3;

    ret1 = pthread_create(&pt1, NULL, (void *)thread1, NULL);
    ret2 = pthread_create(&pt2, NULL, (void *)thread2, NULL);
    ret3 = pthread_create(&pt3, NULL, (void *)thread3, (void *)"thread ...... 3");

    if(ret1==0 && ret2==0 && ret3==0) {
       pthread_join(pt1, NULL);
       pthread_join(pt2, NULL);
       pthread_join(pt3, NULL);
    }

    return (0);
}

執行結果例項

thread .. 1
thread .... 2
thread ...... 3
thread .... 2
thread .. 1
thread ...... 3
thread .... 2
thread .. 1
thread ...... 3
thread .... 2
thread .. 1
thread ...... 3
thread .. 1
thread .... 2
thread ...... 3
thread .... 2
thread .. 1
thread ...... 3
thread .... 2
thread .. 1
thread ...... 3
thread .... 2
thread ...... 3
thread .. 1
thread ...... 3
thread .. 1
thread .... 2
thread ...... 3
thread .. 1
thread .... 2

主要函式:

int pthread_create( pthread_t   *thread,   pthread_attr_t *attr,    void   *(*func),   void   *func_arg);

返回值:  0 成功返回,errorcode 錯誤;

int pthread_join(pthread_t  thread, void **  retval);

返回值:  0 成功返回,errorcode 錯誤;