一 Linux--多线程( 三 )

运行结果如下:

一 Linux--多线程

文章插图
线程在创建过程中不会阻塞 , 主进程会立刻执行 , 那么存在一个问题 , 主进程如果执行完毕 , 那么所有线程都将被释放 , 就可能出现线程还未调度的问题 。(后面会解决)
线程和进程有区别 , 父子进程执行的代码段是一样的 , 但是线程被创建之后执行的是线程处理函数 。
再介绍一个函数:
就像每个进程都有一个进程号一样 , 每个线程也有一个线程号 。进程号再整个系统中是唯一的 , 但是线程号不同 , 线程号只在它所属的进程环境中有效 。
进程号用pid_t数据类型表示 , 是一个非负整数 。线程号则用pthread_t数据类型来表示 , Linux使用无符号长整型数表示 。
实例1: 创建一个线程 , 观察代码运行效果和函数用法
pthread_t pthread_self(void);功能:获取线程号参数:无返回值:调用线程的线程ID#include <stdio.h>#include <pthread.h>#include <unistd.h>void* pthreadrun(void* arg){ char* name = (char*)arg; while (1){printf("%s is running...\n", name);sleep(1); }}int main(){ pthread_t pthread; // 创建新线程 pthread_create(&pthread, NULL, pthreadrun, (void*)"new thread"); while (1){printf("main thread is running...\n");sleep(1); } return 0;}运行结果如下:
一 Linux--多线程

文章插图
实例2: 创建4个线程 , 然后打印出各自的pid和线程id
#include <stdio.h>#include <pthread.h>#include <unistd.h>void* pthreadrun(void* arg){  long id = (long)arg;  while (1){    printf("threaad %ld is running, pid is %d, thread id is %p\n", id, getpid(), pthread_self());    sleep(1);  }}int main(){  pthread_t pthread[5];  int i = 0;  for (; i < 5; ++i)  {    // 创建新线程    pthread_create(pthread+i, NULL, pthreadrun, (void*)i);  }  while (1){    printf("main thread is running, pid is %d, thread id is %p\n", getpid(), pthread_self());    sleep(1);  }  return 0;}运行结果如下:
一 Linux--多线程

文章插图
可以看到六个线程的PID是一样的 , 同属于一个进程 , 但是它们还有一个表示 , LWP(light wighted process) , 轻量级进程的ID 。下面详细介绍 。
进程ID和线程ID