zoukankan      html  css  js  c++  java
  • 多线程学习(一)

    线程的创建

          线程是进程的一个实体,是CPU调度和分派的基本单位,它是比进程更小的能独立运行的基本单位。线程自己基本上不拥有系统资源,只拥有一点在运行中必不可少的资源(如程序计数器,一组寄存器和栈),但是它可与同属一个进程的其他的线程共享进程所拥有的全部资源。

    线程的创建

         使用pthread_create函数。
    1. #include<pthread.h>   
    2. int pthread_create (pthread_t *__restrict __newthread,         // 新创建的线程ID   
    3.                              __const pthread_attr_t *__restrict __attr,// 线程属性   
    4.                              void *(*__start_routine) (void *),          //  新创建的线程从start_routine开始执行   
    5.                              void *__restrict __arg)                           // 执行函数的参数  
    返回值:成功-0,失败-返回错误编号,可以用strerror(errno)函数得到错误信息

    线程的终止(三种方式)

         1.线程从执行函数返回,返回值是线程的退出码

         2.线程被同一进程的其他线程取消

         3.调用pthread_exit()函数退出。这里不是调用exit,因为线程调用exit函数,会导致线程所在的进程退出。

    #include <stdio.h>
    #include <stdlib.h>
    #include <pthread.h>
    #include <unistd.h>
    #include <string.h>
    
    int num = 0;
    
    void *add(void *arg)
    {
     int i = 0, tmp;
     for(; i<500; i++)
     {
      tmp = num + i;
      num = tmp;
      printf("add+1, result is %d
    ", num);
     }
     return 0;
    }
    
    void *sub(void *arg)
    {
     int i = 0, tmp;
     for(; i<500; i++)
     {
      tmp = num - 1;
      num = tmp;
      printf("sub-1, result is %d
    ", num);
     }
     return 0;
    }
    
    int main()
    {
     pthread_t tid_1, tid_2;
     
     int err;
     void *tret;
     
     // 创建线程
     err = pthread_create(&tid_1, NULL, add, NULL);
     if(err != 0)
     {
      printf("pthread_create error.
    ");
      exit(-1);
     }
     
     err = pthread_create(&tid_2, NULL, sub, NULL);
     if(err != 0)
     {
      printf("pthread_create error.
    ");
      exit(-1);
     }
    
     err = pthread_join(tid_1, &tret);
     if(err != 0)
     {
      printf("pthread_join error.
    ");
      exit(-1);
     }
     printf("thread 1 exit code %d
    ", tret);
     
     err = pthread_join(tid_2, &tret);
     if(err != 0)
     {
      printf("pthread_join error.
    ");
      exit(-1);
     }
     printf("thread 2 exit code %d
    ", tret);
     
     
     return 0;
    }
    

     在Linux下编译,g++ -o thread1 thread1.C -lpthread

    运行结果不是想象中的0,因为没有加上锁...

  • 相关阅读:
    Java 集合系列16之 HashSet详细介绍(源码解析)和使用示例
    Java 集合系列15之 Set架构
    Java 集合系列14之 Map总结(HashMap, Hashtable, TreeMap, WeakHashMap等使用场景)
    Java 集合系列13之 WeakHashMap详细介绍(源码解析)和使用示例
    Java 集合系列13之 TreeMap详细介绍(源码解析)和使用示例
    Java 集合系列12之 Hashtable详细介绍(源码解析)和使用示例
    Java 集合系列11之 HashMap详细介绍(二)
    Java 集合系列10之 HashMap详细介绍(源码解析)和使用示例
    Maven01-maven打包Web项目成war文件-tomcat脱机运行启动项目
    Spring -13 -Spring 中常用注解总结
  • 原文地址:https://www.cnblogs.com/eternal1025/p/4432690.html
Copyright © 2011-2022 走看看