簡介
Linux線程是需要連接pthreat庫,線程的使用比進程更靈活,需要注意的是線程間的互斥,或者說是資源共享問題。
C++11之後,C++標準庫也引入了線程,並且使用非常方便,以後再介紹,這裏先發一個簡單的線程示例代碼。
代碼
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
char message[32]={"Hello world!"};
void *thread_function(void *arg);
void *thread_function(void *arg)
{
printf("thread_fonction is runing , argument is %s\n", (char *)arg);
strcpy(message, "marked by thread");
printf("thread_function finished\n");
pthread_exit("Thank you for the cpu time\n");
}
int
main(int argc, char **argv)
{
pthread_t a_thread;
void *thread_result;
if(pthread_create(&a_thread, NULL, thread_function, (void*)message ) < 0)
{
perror("pthread_create error:");
exit(-1);
}
printf("writing for the thread to finish\n");
if(pthread_join(a_thread, &thread_result) < 0)
{
perror("pthread_join error:");
exit(0);
}
printf("in main, thread is exist, marked msg: %s \n", message);
exit(0);
}
編譯
編譯的時候,需要加上pthread線程庫
gcc pthreat.c -o test -lpthread
運行
程序啓動後,主程序中,創建線程,然後等待線程退出,在線程函數裏,會把message字符串修改掉。
./test
in main, writing for the thread to finish
in thread, thread_fonction is runing , argument is Hello world!
in thread, thread_function finished
in main, thread is exist, marked msg: marked by thread