zoukankan      html  css  js  c++  java
  • Linux学习笔记20——第一个多线程程序

    一 什么是线程

      线程:是一个进程内部的一个控制序列。

    二 使用POSIX的注意点

      1 为了使用线程函数库,必须定义宏_REENTRANT,通过定义_REENTRANT来告诉编译器我们需要可重入功能,可重入代码可以被多次调用而仍然正常工作。

      2 在程序中包含头文件pthread.h,并且在编译程序时需要用选项-lpthread来链接线程库。

    三创建线程程序前的准备

      1 创建线程

    #include <pthread.h>
    int pthread_create(pthread_t *thread,           //指向变量中将被写入一个标识符的指针
               pthread_attr_t *attr,         //用于设置线程的属性
               void *(*start_routine)(void*),   //告诉线程将要启动执行的函数
               void *arg               //告诉线程传递给该函数的参数
               );

      2 终止线程

    #include <pthread.h>
    void pthread_exit(void *retval);

      作用:终止调用它的线程并返回一个指向某个对象的指针。

      3 等待线程结束

    #include <pthread.h>
    int pthread_join(pthread_t th,        //指定了将要等待的线程,线程通过pthread_create返回的标识符来指定
              void **thread_return    //是一个指针,它指向另一个指针,而后者指向线程的返回值
              );

    四 第一个线程程序

    #include <stdio.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <string.h>
    #include <pthread.h>
    
    //声明线程函数 void *thread_function(void *arg);
    //线程函数参数
    char message[]="Hello World"; int main(){
       //接收线程函数的返回值
    int res;
       //线程标识符 pthread_t a_thread;
       //指向线程的返回值
    void *thread_result; //创建线程 res=pthread_create(&a_thread,NULL,thread_function,(void *)message); //如果线程没有创建成功,注意pthread_系列函数失败后不是返回-1 if(res!=0){ perror("Thread creation failed"); exit(EXIT_FAILURE); } printf("Waiting for thread to finish... ");
       //等待线程结束 res
    =pthread_join(a_thread,&thread_result);
       //如果等待线程失败
    if(res!=0){ perror("Thread join failed"); exit(EXIT_FAILURE); } printf("Thread joined,it returned %s ",(char *)thread_result); printf("Message is now %s ",message); exit(EXIT_SUCCESS); } void *thread_function(void *arg){ printf("*thread_function is running.Argument was %s ",(char *)arg);
       //睡眠3秒 sleep(
    3);
       //将“Bye!”赋值给参数message strcpy(message,
    "Bye!");
       //退出线程 pthread_exit(
    "Thank you for the CPU time"); }

      运行结果:

  • 相关阅读:
    Python之推导式笔记
    利用ShardingSphere-JDBC实现分库分表--配置中心的实现
    利用ShardingSphere-JDBC实现分库分表
    MGR安装记录
    学习RadonDB源码(三)
    学习RadonDB源码(二)
    学习RadonDB源码(一)
    Spring Cloud学习笔记--Spring Boot初次搭建
    一次单核CPU占用过高问题的处理
    MySQL AutoCommit带来的问题
  • 原文地址:https://www.cnblogs.com/zjzsky/p/3501606.html
Copyright © 2011-2022 走看看