#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
/* 获取当前系统时间*/
void show_time()
{
time_t t = time(NULL);
char *time = ctime(&t);
printf("%s",time);
}
void *fun_1()
{
while(1)
{
sleep(2);
show_time();
printf("this is fun_1\n");
}
}
void *fun_2()
{
while(1)
{
sleep(4);
show_time();
printf("this is fun_2\n");
}
}
int main()
{
pthread_t pid1;
pthread_t pid2;
if(pthread_create(&pid1,NULL,fun_1,NULL))
{
return -1;
}
if(pthread_create(&pid2,NULL,fun_2,NULL))
{
return -1;
}
while(1)
{
sleep(1);
}
return 0;
}
由于pthread 库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a,所以在使用pthread_create()创建线程,以及调用 pthread_atfork()函数建立fork处理程序时,需要链接该库。
输入gcc thread.c -o thread -lpthread,编译之后你就可以看到thread可执行文件,输入./thread即可