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

    • 一个应用程序可以启动若干个线程;
    • 线程,是程序执行的最小单位;
    • 一般一个最简单的程序最少有一个线程,就是程序本身,也是主函数;
    • 一个线程阻塞不会影响另一个线程;
    • 多线程的进程可以尽可能多的利用系统CPU资源。
    /***
    thread.c
    ***/
    #include<stdio.h>
    #include<stdlib.h>
    #include<pthread.h>
    #include<unistd.h>
    
    int *thread(void *arg)
    {
        pthread_t newThid;
        newThid = pthread_self();
        printf("this is a new thread,thread ID = %lu
    ",newThid);
        return NULL;
    }
    
    int main()
    {
        int iRet = 0;
        pthread_t thid;
        printf("main thread,ID is %lu
    ",pthread_self());
        iRet = pthread_create(&thid,NULL,(void *)thread,NULL);
        if(iRet != 0)
        {
            printf("thread creation failed
    ");
            exit(1);
        }
        sleep(1);
        exit(0);
    }

    Attention:编译时需要加上-lpthread来连接libpthread.so动态库,否则会报错。

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

    函数参数:

      pthread_t 代表创建线程的唯一标识,是一个结构体,需要创建好以后将结构体的指针传递过去;

      pthread_attr_t:代表创建这个线程的一些配置,比如分配栈的大小,一般设置位NULL,表示默认的创建线程的配置;

      start_routine:代表一个函数的地址,创建线程时,会调用这个函数,函数的返回值时void*,函数的参数也是void*;

      arg:代表调用第三个函数传递的参数。

    函数的返回值:

      函数成功返回0,不等于0表示函数调用失败,此时可以通过strerror(error)可以打印出具体的错误。

    ATTENTION:每个函数都有一份errno副本,不同的线程拥有不同的errno

  • 相关阅读:
    解除对80端口的占用
    php排序算法
    Jquery异步请求数据实例
    C# winform 递归选中TreeView子节点
    C# WinFrom 编写正则表达式验证类
    c# winfrom 委托实现窗体相互传值
    [转]我的第一个WCF
    计算字符串中子串出现的次数
    JQuery中的html(),text(),val()区别
    Crystal Report制作使用
  • 原文地址:https://www.cnblogs.com/wanghao-boke/p/11251709.html
Copyright © 2011-2022 走看看