线程控制知识点总结(上)

线程是什么?

 线程是计算机中独立运行的最小单位,运行时占用很少的系统资源,也可以认为是操作系统分配CPU时间的基本单位
 单核cpu在执行多个线程时是来回切换的,每个线程只有在系统分配给它的时间片内才能执行线程中的代码。

多线程比多进程的优点:

每个进程都有自己的独立空间,而同一进程内的线程共享进程的地址空间
线程间的切换速度远快过进程间的
进程间的数据空间相互独立,彼此间通信要经过操作系统,而线程数据可以直接提供给其他线程使用
提高程序的响应速度
提高多处理器效率
改善程序结构

线程的私有数据:

 线程号
 寄存器
 堆栈
 信号掩码
 优先级
 线程私有的存储空间

线程创建:

函数 pthread_create(pthread_t * thread,pthread_attr_t * attr,void * (* start_routine)(void *),void *arg );
创建线程代码:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
int thread(void *arg)
{
  pthread_t newthid;
  newthid = pthread_self();
  printf("这是一个新的进程,进程ID为:%u\n",newthid);
  return 0;
}
int main()
{
  pthread_t thid;
  printf("主进程,进程ID为:%u \n",pthread_self() );
  if(pthread_create(&thid,NULL,(void *)thread,NULL)!=0)
  {
    printf("创建进程失败\n");
    exit(1);
  }
  sleep(1);
  exit(0);
}

运行结果:

主进程,进程ID为:421861120 
这是一个新的进程,进程ID为:413746944

限制函数执行次数

函数:pthread_once( pthread_once_t once_control,void( init_routine)(void) )
代码:

#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
pthread_once_t once = PTHREAD_ONCE_INIT;
void run(void)
{
  printf("程序正在运行,线程ID: %u \n",pthread_self());
}
void * thread1(void *arg)
{
  pthread_t thid = pthread_self();           //thid获取函数,为当前进程ID
  printf("当前线程的ID为:%u\n",thid);         //输出当前线程ID
  pthread_once(&once,run);                  //保证线程函数run()函数只运行一次
  printf("线程1结束\n");
}
void * thread2(void *arg)
{
  pthread_t thid = pthread_self();
  printf("当前线程的ID为:%u\n",thid);      //第二个线程ID
  pthread_once(&once,run);                 //因为在第一个函数中已经使用函数对run函数在该线程中只执行一次,所以就算这个函数也使用了run函数,但是并没有执行
  printf("线程2结束\n");
}
int main()
{
  pthread_t thid1,thid2;
  pthread_create(&thid1,NULL,thread1,NULL);
  pthread_create(&thid2,NULL,thread2,NULL);
  sleep(3);
  printf("主线程退出\n");
  exit(0);
}

运行结果:

当前线程的ID为:1350207232
程序正在运行,线程ID: 1350207232 
线程1结束
当前线程的ID为:1341814528
线程2结束
主线程退出

线程终止

 有两种方法可以使线程终止,第一种通过retur从线程函数返回,第二种是通过调用函数pthread_exit()使线程退出
  在主线程中,如果从main函数返回或是调用了exit函数退出主线程,则整个进程将终止,进程中所有线程也会终止。
  如果主线程调用pthread_exit函数,则仅仅是主线程消亡,进程不会结束,进程内的其他线程也不会终止,所有线程结束后,进程才会结束。

自动释放资源函数

pthread_cleanup_push ( )
pthread_cleanup_pop ( )
两个函数必须成对出现,且必须位于程序的同一代码段中。

线程间的同步问题

一般情况下,线程中各个进程的运行是相互独立的,线程的终止并不会相互告知,终止的线程所占用的资源不会随着线程的终止而归还系统,而是仍为线程所在的进程所有。
函数pthread_join()函数用来等待一个线程的结束
一个线程仅允许一个线程使用等待函数
代码:

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<unistd.h>
void assi(void *arg)
{
  printf("我在帮忙做一些工作\n");
  sleep(3);
  pthread_exit(0);
}
int main(void)
{
  pthread_t ass;
  int status;
  pthread_create(&ass,NULL,(void *)assi,NULL);
  pthread_join(ass,(void *)&status);         //使用pthread_join()函数,主线程等待assi线程结束再进行
  printf("函数结束退出码:%d\n",&status);
  return 0;
}

运行结果:

我在帮忙做一些工作
函数结束退出码:606147156
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值