多线程编程-c语言

版权声明:转载请注明出处: https://blog.csdn.net/qq_38701476/article/details/82918894

适用与linux系统
1. 了解基本概念
 进程:是计算机所执行的一个任务的描述,是面向操作系统的最小单位,操作系统能执行很多进程.运行自己写的一份代码程序,就是让操作系统执行一个自己程序的进程.操作系统会根据程序分配定量的资源.
 线程:面想程序(进程)的,把一个程序分成多个线程可以实现并发式,多任务运行.

  • 注意:把一个程序该成多线程之后,并不会仅仅缩短我们所理解的时间,我们可以这样想.对于一个程序,系统给我们分配的资源的定量的,因此要是满载跑的话不管再分成多少个并发,他们所完成的时间也可以说极限是一定的.但是我们应用层的程序很容易遇到一种情况,程序运行并不仅仅自动就运行完,可能需要人机交互,或者多人访问,又或者其他一些造成程序某一部分费时,这是运用多线成就完美解决了这一难题.

2.pthread运用
pthread是c语言中实现多线程途径
先附上一段代码

#include<stdio.h>
#include<pthread.h>
void pri1(){
	for(int i=0;i<10;i++)
	printf("+++\n");
}
void pri2(){
	for(int i=0;i<10;i++)
	printf("---\n");
}
int main()
{
	pthread_t id,id2;
	pthread_create(&id,NULL,(void *)pri1,NULL);
	pthread_create(&id2,NULL,(void *)pri2,NULL);
	pthread_join(id,NULL);
	printf("******\n");
	return 0;
}

linux下终端编译运行多线程命令

gcc 1.c -lpthread -o 1.out //假如程序名字是1.cpp,进行编译
./1.out//执行

说明:

  1. extern int pthread_create __P ((pthread_t *__thread, __const pthread_attr_t *__attr, void (__start_routine) (void *), void *__arg));
    创建多线程的命令.第一个参数为多线程指针,代表该线程标识符;第二个多线程属性设置,可以为NULL,第三个为多线成起始运行地址,函数要强制转换指针类型(void *);第四个参数为运行的参数,注意也是一个指针类型.
  2. pthread_t ;进程型变量名,类似int,char
  3. pthread_join ((pthread_t id, void **__thread_return));等待一个线程的结束.第一个参数线程表示符,第二个参数为线程返回值
  4. void pthread_exit(void *rval_ptr);退出进程(也就是说程序停止类似return);

3. 程序线程属性优先级简单讲解
参考文章1
参考文章2
线程属性非透明的,只能固定调用相关的函数(类似c++的类),先创建属性变量
线程具有属性,用pthread_attr_t表示,在对该结构进行处理之前必须进行初始化,在使用后需要对其去除初始化。下面是对属性进行初始话函数pthread_attr_t();函数里面的参数,后面可以设置默认值

typedef struct
{
       int                       detachstate;   // 线程的分离状态
       int                       schedpolicy;   // 线程调度策略
       structsched_param         schedparam;    // 线程的调度参数
       int                       inheritsched;  // 线程的继承性
       int                       scope;         // 线程的作用域
       size_t                    guardsize;     // 线程栈末尾的警戒缓冲区大小
       int                       stackaddr_set; // 线程的栈设置
       void*                     stackaddr;     // 线程栈的位置
       size_t                    stacksize;     // 线程栈的大小
} pthread_attr_t;

对于优先级,一般说来,我们总是先取优先级,对取得的值修改后再存放回去。下面附上一个代码

#include <pthread.h> 
#include <sched.h> 
pthread_attr_t attr; //线程属性变量
pthread_t tid; 
sched_param param; 
int newprio=20; 
pthread_attr_init(&attr); //
pthread_attr_getschedparam(&attr, &param); //取出优先级
param.sched_priority=newprio; //进行修改
pthread_attr_setschedparam(&attr, &param);//设置进去 
pthread_create(&tid, &attr, (void *)myfunction, myarg);

注:多线程运行的话可能会出现一些问题,我在linux终端运行的很多次的时候会出现几次有一个线程没有运行的.具体我就不清楚为啥没运行了O(∩_∩)O哈哈~

猜你喜欢

转载自blog.csdn.net/qq_38701476/article/details/82918894
今日推荐