• 【Linux环境】创建一个简单多线程程序



    先沾代码,没时间了,抽时间把理论补上。




    源代码如下:
    #include <stdio.h> #include <pthread.h> /* 定义线程要执行的函数,p_arg为接收线程传递过来的数据 */ void *Thread1_fuc(void *p_arg) { printf("我线程1在执行找豆豆操作\n"); return "我线程1执行成功了哦\n"; } void *Thread2_fuc(void *p_arg) { printf("我线程2在执行打豆豆操作\n"); return "我线程2执行成功了哦\n"; } int main() { int res = 0; pthread_t mythread1,mythread2; void *p_thread_result = NULL; /* 1.创建一个线程, &mythread1:要创建的线程 NULL:不修改新建线程的任何属性 ThreadFun:新建的线程要执行的动作 NULL:不传递给ThreadFun()函数任何参数 res:返回值,res为0表示创建线程成功了,否则代表创建失败 */ res = pthread_create(&mythread1, NULL, Thread1_fuc, NULL); if (0 != res) { printf("创建线程1失败\n"); return 0; } res = pthread_create(&mythread2, NULL, Thread2_fuc, NULL); if (0 != res) { printf("创建线程2失败\n"); return 0; } /* 2.等待指定线程执行完毕 mythread:指定等待的线程; &p_thread_result:接收ThreadFun()函数的返回值, 或者接收pthread_exit()函数指定的值 返回值res为0表示函数执行成功,反之则执行失败 */ res = pthread_join(mythread1, &p_thread_result); //输出线程执行完毕后返回的数据 printf("%s\n", (char*)p_thread_result); res = pthread_join(mythread2, &p_thread_result); //输出线程执行完毕后返回的数据 printf("%s\n", (char*)p_thread_result); printf("主线程执行结束\n"); return 0; } /* 注意: 1. 编译命令:gcc c_thread_1.c -o hello -lpthread (命令中要加-plthread参数,否则会导致程序连接失败) 编译程序包括 预编译, 编译,汇编,链接,包含头文件了,仅能说明有了线程函数的声明, 但是还没有实现, 加上-lpthread是在链接阶段,链接这个库。用-phtread也行,并且建议,向后兼容。 */
  • 相关阅读:
    可变参数模板的递归解析
    在Ubuntu上安装多个版本的g++ 并进行默认版本切换
    不错的威盾PHP加密专家解密算法
    文章相关性分析详细介绍
    c#连接mysql中文乱码解决方案(MySql.Data.dll)
    firefox用12306Helper 0.2结合ie tab+自动订火车票和完成支付全攻略
    Nutch命令大全
    Jtable利用SetModel进行数据绑定
    在php中使用CKEDITOR在线编辑器
    Nutch1.2搜索引擎使用详解
  • 原文地址:https://www.cnblogs.com/coreLeo/p/16018952.html
Copyright © 2020-2023  润新知