zoukankan      html  css  js  c++  java
  • linux下的线程学习(一)

    线程标识

    #include<pthread.h>

    int pthread_equal(    //用于比较两个线程是否相等

    pthread_t tid1, //线程id=tid1

    pthread_t tid2);//线程id=tid2

    pthread_t pthread_self(void);    //用于返回自身的线程id

    线程创建

    #include<pthread.h>

    int pthread_create(   //用于创建线程

    pthread_t *restrict tidp, //线程id

    const pthread_attr_t *restrict attr,//属性

    void *(*start_rin)(void*),//线程开始函数

    void *restrict arg);//函数的传入参数【如果想参入多个数据,用结构体】

    实例

     1 #include <iostream>
     2 #include <pthread.h>
     3 
     4 pthread_t ntid;
     5 
     6 void printids(const char *s) {
     7 
     8   pid_t pid;
     9   pthread_t tid;
    10 
    11   pid = getpid();
    12   tid = pthread_self();
    13   printf("%s pid %u tid %u (0x%x)
    ", s, (unsigned int)pid, 
    14       (unsigned int)tid, (unsigned int)tid);
    15 }
    16 
    17 void* thr_fn(void *arg) {
    18   
    19   printids("new thread: ");
    20   return ((void*)0);
    21 }
    22 
    23 int main() {
    24   
    25   int err;
    26   err = pthread_create(&ntid, NULL, thr_fn, NULL);
    27   if(err != 0) {
    28     printf("can't create thread: %s
    ", strerror(err));
    29   }
    30   printids("main thread: ");
    31   sleep(1);
    32   return 0;
    33 }

    g++ thread.cpp -o thread -lpthread

    ./thread

    main thread:  pid 30466 tid 3892546496 (0xe8038bc0)
    new thread:  pid 30466 tid 1109510464 (0x4221c940)

    简单的线程使用实例。

  • 相关阅读:
    SVN 安装 使用指南
    使用angular-cli快速搭建项目命令
    angular 路由的引用
    c#默认类的修饰符。
    c#
    js改变dom对象样式
    jquery常用函数
    PHP 文件上传
    php 表单代码
    Python 条件语句
  • 原文地址:https://www.cnblogs.com/xuxu8511/p/3360272.html
Copyright © 2011-2022 走看看