lunux多线程编程

1.进程与线程

  1)用户空间角度:

  进程:fork()创建进程,在创建时,重新申请了内存空间,copy了父进程的所有信息。

  线程:pthread_create()创建进程时,只申请自己的栈空间。

  2)内核空间:

  对内核空间,两者都有自己的pid,因此内核空间不区分。

2.基本函数:

  1)创建线程:

  #include <pthread.h>

  extern in t pthread_create(pthread_t *tidp,const pthread_attr_t *attr,(void*)(*start_rtn)(void*),void  *arg

  第1个参数: 线程id

  第2个参数:用来设置线程属性,通常为NULL

  第3个参数:需要创建线程的执行代码地址

  第4个参数:线程执行参数

  pthread.h支持的是POSIX,编译时加-lpthread

#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/syscall.h>
struct data{
        int i;
        int j;
};
void *hello(struct data *str)
{
        printf("child,  the tid=%lu, pid=%ld\n",pthread_self(),syscall(SYS_gettid));
        printf("arg.i=%d\narg.j=%d \n",str->i,str->j);
        sleep(1);
}

int main(int agrc,char *agrv[])
{
        struct data test;
        pthread_t thread_id;
        test.i=20;
        test.j=50;
        pthread_create(&thread_id,NULL,(void*)*hello,&test);
        printf("parent, the tid=%lu,pid=%ld\n",pthread_self(),syscall(SYS_gettid));
        pthread_join(thread_id,NULL);
}

  2)线程退出:

  extern void pthread_exit(void *_retval),参数为线程取消状态。

  int pthread _cancel(pthread_t thread)

  线程取消的清理:

  int pthread_cleanup_push(void (*routine)(void*),void *arg)

  int pthread_cleanup_pop(int execute)

 1 #include<pthread.h>
 2 #include<unistd.h>
 3 #include<stdlib.h>
 4 #include<stdio.h>
 5
 6 void cleanup()
 7 {
 8         printf("cleanup\n");
 9 }
10 void *test_cancel(void)
11 {
12         pthread_cleanup_push(cleanup,NULL);
13         printf("test_cancel\n");
14         while(1)
15         {
16                 printf("test message\n");
17                 sleep(1);
18         }
19         pthread_cleanup_pop(1);
20 }
21 int main()
22 {
23         pthread_t tid;
24         pthread_create(&tid,NULL,(void *)test_cancel,NULL);
25         sleep(2);
26         pthread_cancel(tid);
27         pthread_join(tid,NULL);   // pthread_join()等待线程执行
28 }

  3)线程与私有数据:

  int pthread_key_create(pthread_key_t *key, void (*destructor)(void*))   //创建私有数据

  int pthread_key_delete(pthread_key_t key)  //删除私有数据

  int pthread_setspecific(pthread_key_t key,const void *pointer)  //读,pointer是与key相关联的

  int pthread_getspecific(pthread_key_t key)  //写

3.互斥锁:以排他的方式防止共享数据并发的访问

  1)初始化:

  #include <pthread.h>

  int pthread_mutex_init(pthread_mutex_t *restrict mutex,const pthread_mutexattr_t *restrict attr)

  第1个参数:所要指向的互斥锁指针

  第2个参数:指向属性对象的指针,如NULL使用默认属性

  2)申请互斥锁:

  int pthread_mutex_lock(pthread_mutex_t  *mutex)       //阻塞方式申请

  int pthread_mutex_trylock(pthread_mutex_t  *mutex)  //非阻塞方式申请

  3)释放互斥锁:

  int pthread_mutex_unlock(pthread_mutex_t  *mutex)

 1 #include <stdio.h>
 2 #include <unistd.h>
 3 #include <stdlib.h>
 4 #include <pthread.h>
 5 #include <semaphore.h>
 6 #include <string.h>
 7
 8 void *thread_function(void *arg);
 9
10 pthread_mutex_t work_mutex;
11
12 #define WORK_SIZE 1024
13 char work_area[WORK_SIZE];
14 int time_to_exit = 0;
15
16 int main(int argc,char *argv[])
17 {
18     int res;
19     pthread_t a_thread;
20     void *thread_result;
21     res = pthread_mutex_init(&work_mutex, NULL); //init mutex
22     if (res != 0)
23         {
24         perror("Mutex initialization failed");
25         exit(EXIT_FAILURE);
26     }
27     res = pthread_create(&a_thread, NULL, thread_function, NULL);//create new thread
28     if (res != 0)
29         {
30         perror("Thread creation failed");
31         exit(EXIT_FAILURE);
32     }
33     pthread_mutex_lock(&work_mutex);                    //lock the mutex
34     printf("Input some text. Enter ‘end‘ to finish\n");
35     while(!time_to_exit)
36         {
37         fgets(work_area, WORK_SIZE, stdin);             //get a string from stdin
38         pthread_mutex_unlock(&work_mutex);              //unlock the mutex
39         while(1)
40                 {
41             pthread_mutex_lock(&work_mutex);    //lock the mutex
42             if (work_area[0] != ‘\0‘)
43                         {
44                 pthread_mutex_unlock(&work_mutex);      //unlock the mutex
45                 sleep(1);
46             }
时间: 2024-08-24 08:43:38

lunux多线程编程的相关文章

多线程编程核心技术总结(读周志明书籍的总结)

多线程编程核心技术总结 1.Java多线程基本技能 1.1进程和线程的概念: 进程是独立的程序,线程是在进程中独立运行的子任务. 1.2使用多线程 1.2.1实现方法:继承Thread类,重写Runnable接口. 1.2.2线程安全问题:并发修改公共的实例变量,i++,i-- 1.3线程Thread类的一些方法: currentThread() 放回代码段正在被那个线程调用 isAlive() 判断线程是否处于活动状态 sleep() 使得当前线程退出CPU片段,等待获取锁 1.4停止线程 1

Java基础知识—多线程编程(五)

概述 Java 给多线程编程提供了内置的支持.一个多线程程序包含两个或多个能并发运行的部分.程序的每一部分都称作一个线程,并且每个线程定义了一个独立的执行路径.使用多线程也是为了充分的利用服务器资源,提高工作效率. 线程生命周期 线程是一个动态执行的过程,它也有一个从产生到死亡的过程. 新建状态: 使用 new 关键字和 Thread 类或其子类建立一个线程对象后,该线程对象就处于新建状态.它保持这个状态直到程序 start() 这个线程. 就绪状态: 当线程对象调用了start()方法之后,该

第73课 Qt中的多线程编程

1. QThread类 (1)QThread是一个跨平台的多线程解决方案 (2)QThread以简洁易用的方式实现多线程编程 2. QThread中的关键成员函数 (1)virtual void run() :线程函数,用于定义线程功能(执行流). (2)void start():启动函数,将线程入口地址设置为run函数.启动线程,新线程开始执行run函数. (3)int exec():进入事件循环,直至调用exit().返回线程退出事件循环的返回码. (4)void terminate():强

多线程编程(进程和线程)

多线程编程(进程和线程) 1.进程:指一个内存中运行的应用程序,每个进程都有自己独立的一块内存空间,一个进程可以启动多个线程. 2.线程:指程序中一个执行流程,一个进程中可以运行多个线程. 一.创建线程(两种方式) 二.线程的5种状态( New,Runnable,Running,Block,Dead ): 三.线程的优先级 四.守护线程 /精灵线程/后台线程 五.方法 六.同步代码锁(synchronized) 一.创建线程(两种方式): 方式1:采用继承Thread的方法 第一,继承 Thre

多线程编程基础知识

多线程编程基础知识 http://www.cnblogs.com/cy163/archive/2006/11/02/547428.html 当前流行的Windows操作系统能同时运行几个程序(独立运行的程序又称之为进程),对于同一个程序,它又可以分成若干个独立的执行流,我们称之为线程,线程提供了多任务处理的能力.用进程和线程的观点来研究软件是当今普遍采用的方法,进程和线程的概念的出现,对提高软件的并行性有着重要的意义.现在的大型应用软件无一不是多线程多任务处理,单线程的软件是不可想象的.因此掌握

iOS多线程编程

1. 进程,线程, 任务 进程:一个程序在运行时,系统会为其分配一个进程,用以管理他的一些资源. 线程:进程内所包含的一个或多个执行单元称为线程,线程一般情况下不持有资源,但可以使用其所在进程的资源. 任务:进程或线程中要做的事情. 在引入线程的操作系统中,通常把进程作为分配资源的基本单位,而把线程作为独立运行和独立调度的基本单位. 线程比进程更小,对其调度的开销小,能够提高系统内多个任务的并发执行程度. 一个程序至少有一个进程,一个进程至少有一个线程.一个程序就是一个进程,而一个程序中的多个任

多线程编程1-NSThread

前言 每个iOS应用程序都有个专门用来更新显示UI界面.处理用户触摸事件的主线程,因此不能将其他太耗时的操作放在主线程中执行,不然会造成主线程堵塞(出现卡机现象),带来极坏的用户体验.一般的解决方案就是将那些耗时的操作放到另外一个线程中去执行,多线程编程是防止主线程堵塞,增加运行效率的最佳方法. iOS中有3种常见的多线程编程方法: 1.NSThread 这种方法需要管理线程的生命周期.同步.加锁问题,会导致一定的性能开销 2.NSOperation和NSOperationQueue 是基于OC

Android多线程编程(一)——多线程基础

什么是进程 一个进程是一个独立(self contained)的运行环境,它可以看作一个程序或者一个应用. 什么是线程 而线程是进程中执行的一个任务,Java运行环境是一个包含了不同累和程序的单一进程.线程可以被称为轻量级进程.线程需要较少的资源来创建和驻留在进程中,并且可以共享进程中的资源. Android线程 Android的线程,实际上和Java的多线程编程并没有什么本质上的不同.当我们需要执行一些耗时操作,比如说发起一条网络请求时,考虑到网速等其他原因,服务器未必会立刻响应我们的请求,如

《Java多线程编程核心技术》推荐

写这篇博客主要是给猿友们推荐一本书<Java多线程编程核心技术>. 之所以要推荐它,主要因为这本书写得十分通俗易懂,以实例贯穿整本书,使得原本抽象的概念,理解起来不再抽象. 只要你有一点点Java基础,你就可以尝试去阅读它,相信定会收获甚大! 博主之前网上找了很久都没完整pdf电子版的,只有不全的试读版,这里博主提供免费.清晰.完整版供各位猿友下载: http://download.csdn.net/detail/u013142781/9452683 刚刚已经提到,<Java多线程编程核