zoukankan      html  css  js  c++  java
  • linux多线程

    1、进程与线程

    这是个老生常谈的话题,我们只需要记住:

    进程可是一个资源的基本单位,而线程是程序调度的基本单位,一个进程内部的线程之间共享进程获得的时间片。线程拥有自己的栈,因为线程有自己的局部变量,其他的资源(文件描述字,全局变量等)和其他线程共享。

    2、有关线程的函数

    int pthread_create(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);

    参数说明:

    thread:指向pthread_create类型的指针,用于引用新创建的线程。

    attr:用于设置线程的属性,一般不需要特殊的属性,所以可以简单地设置为NULL。

    *(*start_routine)(void *):传递新线程所要执行的函数地址。

    arg:新线程所要执行的函数的参数。

    调用如果成功,则返回值是0,如果失败则返回错误代码。

    void pthread_exit(void *retval);

    参数说明:

    retval:返回指针,指向线程向要返回的某个对象。

    线程通过调用pthread_exit函数终止执行,并返回一个指向某对象的指针。不能指向局部变量…… 如下栗子:

    View Code
    void threadFunc(char * arg){
        char result = 'd';
        printf("%s\n", arg);
        
        pthread_exit(&result);
    }
    
    
    int main(){
        pthread_t t1;
        void * res;
        int s;
        
        s = pthread_create(&t1, NULL, (void *)threadFunc, (void *)"hello world");
    
        if(s != 0) printf("create failed\n");
    
        s = pthread_join(t1, &res);
    
        if(s != 0) printf("join failed\n");
        
        printf("thread return %c",*((char *)res));
    
        return 0;
    }

    int pthread_join(pthread_t thread, void ** retval);

    参数说明:

    thread: 线程标识符,即线程ID,标识唯一线程。   

    retval: 用户定义的指针,用来存储被等待线程的返回值。

    来源百度百科:代码中如果没有pthread_join主线程会很快结束从而使整个进程结束,从而使创建的线程没有机会开始执行就结束了。加入pthread_join后,主线程会一直等待直到等待的线程结束自己才结束,使创建的线程有机会执行。   所有线程都有一个线程号,也就是Thread ID。其类型为pthread_t。通过调用pthread_self()函数可以获得自身的线程号。

  • 相关阅读:
    12.静态目录
    11.Git线上操作
    10.分离的前后台交互
    09.后台主页应用
    08.前端主页
    爬虫介绍
    python2与python3爬虫中get与post对比
    HTML+CSS+JavaScript
    数据库 Mysql-mongodb-redis
    时频工具箱介绍与使用
  • 原文地址:https://www.cnblogs.com/yujinghui/p/2738830.html
Copyright © 2011-2022 走看看