/************************************************************************* #include <pthread.h> int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void * arg), void *arg); 功能:创建一个线程 参数: thread 线程id变量取地址 attr 线程的属性,NULL表示默认值 start_routine 线程执行的函数 需要自己定义为 void *(fun) (void * arg)类型的函数 然后把函数名传进去,这个函数就是线程执行的内容 arg 传递给线程执行的参数 可以接收任意类型的指针,最终值传递给了线程函数 返回值: 成功 0 失败 errno值 Compile and link with -pthread gcc 01_pthread_create.c -lpthread 编译时候需要加上链接库 **************************************************************************/ //代码: #include <stdio.h> #include <pthread.h> //pthread_create() 创建线程 #include <unistd.h> //sleep() 休眠时间,以秒为单位 //自定义一个线程函数 void *my_pthread(void *arg) { for (int i=1;i<=20;i++) { printf("我是线程 %d \n",i); sleep(1); } } int main(int argc, const char *argv[]) { pthread_t tid; //定义一个线程类型的变量 pthread_create(&tid,NULL,my_pthread,NULL); //创建线程 for (int i=1;i<=30;i++) { printf("我是main线程 %d \n",i); sleep(1); } return 0; }
浙公网安备 33010602011771号