备注:vscode通过ssh连接虚拟机中的ubuntu,ubuntu-20.04.3-desktop-amd64.iso
函数pthread_create()
// pthread.h中的函数pthread_create()extern int pthread_create
(pthread_t *__restrict __newthread, // 线程标识符const pthread_attr_t *__restrict __attr, // 线程属性void *(*__start_routine) (void *), // 线程函数指针void *__restrict __arg // 线程函数指针的参数
)
__THROWNL __nonnull ((1, 3));
代码段
#include<stdio.h>
#include<math.h>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>// 线程函数
void * th_fn(void * arg)
{int distance = (int)arg; // 龟兔赛跑的距离int i;// 对于turtle线程和rabbit线程来说,局部变量i不共享for(i=1; i<=distance; i++){printf("线程%lx run %d\n", pthread_self(), i);int time = (int)(drand48() * 100000);usleep(time); // 睡眠time微秒}return (void *) 0;
}int main(void)
{int err; // err用于接收pthread_create()的返回值pthread_t rabbit, turtle;// 创建turtle线程if((err = pthread_create(&turtle, NULL, th_fn, (void *)50)) != 0)perror("pthread_creat() error!");// 创建rabbit线程if((err = pthread_create(&rabbit, NULL, th_fn, (void *)50)) != 0)perror("pthread_creat() error!");// 主控线程pthread_join(rabbit, NULL); // 主控线程等待rabbit线程执行完成pthread_join(turtle, NULL); // 主控线程等待turtle线程执行完成printf("Main control thread id:%lx\n", pthread_self());printf("finished!\n");return 0;
}
对代码段进行编译:
gcc test_pthread_1.c -o test_pthread_1 -l pthread