多线程实现相关函数

xiaoxiao2021-02-28  97

1 线程的创建 pthread_create 函数用于创建线程 表头文件:#include<pthread.h> 定义函数:int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void*(*start_rtn)(void),void*restrict arg) 函数说明:pthread_t *restrict tidp  要创建线程的线程ID指针 (&tid)          const pthread_attr_t *restrict attr  创建线程时的线程属性(NULL)          void*(*start_rtn)(void)  返回值是void类型的指针函数   (server_request)          void*restrict arg  start_rtn的形参  ((void *)clientfd) 返回值: 调用成功后返回0,其他都表示错误,检测到如下情况,pthread_create()将失败并返回相应值          EAGAIN 超出系统限制,线程创建太多          EPERM  调用者没有适当权限设置所需的参数或调度策略          EINVAL 描述 tattr 的值无效 2 线程终止 pthread_exit用于线程终止 定义函数: void pthread_exit(void *retval); 函数说明:使用 pthread_exit退出线程,这是线程的主动行为;由于进程中的多个线程是共享数据段,因此通常在线程退出后,退出线程所占用的资源          并不会随着线程终止而释放,但可以用pthread_join函数来同步并释放 返回值:pthread_exit()调用线程返回值,可由其他函数如pthread_join来检索获取 退出方式有三种: 线程执行函数返回,返回值是线程的退出吗                 线程被同一进程的其他线程取消                 调用pthread_exit()函数退出 3 线程等待 pthread_join用于线程等待 定义函数:pthread_join(thread_t tid,void **status) 函数说明:参数tid 指要等待的线程ID,线程等待必须在当前进程中,不能在分离进程中,当status部位NULL时,status指向某个位置,在成功返回时,          该位置设为终止线程的退出状态 返回值:成功返回0;不成功返回相应的值         ESRCH  没有找到给定线程ID相应的线程

        EDEADLK  出现死锁

        EINVAL  给定线程ID对应线程为分离线程

/* 创建两个线程,实现每隔一秒实现一次打印 */ #include<stdio.h> #include<pthread.h> void *mythread1(void) { int i; for (i=0; i<100; i++) { printf("this is first pthread\n"); sleep(1); } } void *mypthread2 (void) { int i; for (i=0; i<100; i++) { printf("this is secend pthread\n"); sleep(1); } } int main() { int i = 0, ret = 0; pthread_t tid1,tid2; /*创建线程1*/ ret = pthread_create(&tid1, NULL, (void*)mypthread1, NULL) if (ret) { printf("create pthread error!\n"); return 1; } /*创建线程2*/ ret = pthread_create(&tid1, NULL, (void*)mypthread2, NULL) if (ret) { printf("create pthread error!\n"); return 1; } pthread_join(tid1,NULL); pthread_join(tid2,NULl); return 0; }                
转载请注明原文地址: https://www.6miu.com/read-81408.html

最新回复(0)