#include<stdio.h>
#define NUM 6
int main()
{
void print_msg(char*);
print_msg("hello,");
print_msg("world!");
}
void print_msg(char* m)
{
int i;
for(i=0;i<NUM;i++)
{
printf("%s",m);
fflush(stdout);
sleep(1);
}
}
下圖反映了程序的執行流程:

執行結果:
hello,hello,hello,hello,hello,hello,world!world!world!world!world!world!
那么如果想同時執行兩個對於print_msg函數的調用,就想建立兩個新的進程一樣,那該怎么辦?這種思想清楚的體現在下圖:

那么怎么才能達到這種效果呢?
以下兩個函數都包含在頭文件pthread.h中
我們可以使用函數pthread_create創建一個新的線程:
函數原型:
int pthread_create( pthread_t
*thread, pthread_attr_t *attr, void *(*func), void *arg);
參數:
thread 指向pthread_t類型變量的指針,
typedef unsigned long int pthread_t, pthread_t用於聲明線程ID
attr 指向pthread_attr_t類型變量的指針,或者為NULL
func 指向新線程所運行函數的指針
arg 傳遞給func的參數
返回值
0 成功返回
errcode 錯誤
我們可以使用函數pthread_join等待某進程結束:
#include<stdio.h>
函數原型:
int pthread_join(pthread_t thread, void ** retval);
參數:
thread 所等待的進程
retval 指向某存儲線程返回值的變量
返回值: 0
成功返回
errorcode 錯誤
#include<pthread.h>
#define NUM 6
int main()
{
void print_msg(void*);
pthread_t t1,t2;
pthread_create(&t1,NULL,print_msg,(void *)"hello,");
pthread_create(&t2,NULL,print_msg,(void *)"world!\n");
pthread_join(t1,NULL);
pthread_join(t2,NULL);
}
void print_msg(void* m)
{
char *cp=(char*)m;
int i;
for(i=0;i<NUM;i++)
{
printf("%s",m);
fflush(stdout);
sleep(1);
}
}
運行結果:
hello,world!
hello,world!
hello,world!
hello,world!
hello,world!
hello,world!
C語言有一次拓展了我的視野,多線程的問題還有很多,像線程間的分工合作、使用互斥機制保證線程間數據的安全共享、使用條件變量同步線程間的數據傳輸、傳遞多個參數給線程等,若讀者有興趣,可自行深入。