Unix/Linux系统编程第四章学习笔记

Unix/Linux系统编程第四章学习笔记

作者:20191322wyl

知识点总结

并行计算导论

Linux 环境中有很多应用程序和很多进程,其中最重要的是客户端网络/服务器。 多进程服务器是指当客户端发出请求时,服务器使用子进程来处理客户端的请求。 父进程继续等待来自其他客户端的请求。 这种方法的优点是服务器可以在客户端请求时管理客户端,特别是在交互式客户端/服务器系统中。 对于 TCP 服务器,客户端和服务器之间的连接可能不会立即关闭。 客户端发送数据后可以关闭连接。 在此期间,服务器端进程被阻塞,操作系统可能会设置其他计划。 此时的客户服务流程。 与循环服务器相比,该服务的性能得到了显着提高。

顺序算法与并行算法

并行性与并发性

通常,并行算法只识别可并行执行的任务,但是它,但。然而,,但,比如多处理器或多核系统。在单 CPU 系统中,一次只能执行一个任务。在这种情况下,不同的任务只能并发执行、即在逻辑上并行执行。在单CPU系统中,并发性是通过多任务处理来实现的。

线程

线程的原理

线程是某进程同一地址空间上的独立执行单元。

线程的优缺点

与进程相比,线程有许多优点。

  • 线程创建和切换速度更快
  • 线程的响应速度更快
  • 线程更适合并行计算

线程的缺点

  • 由于地址空间共享,线程需要来自用户的明确同步。
  • 许多库函数可能对线程不安全。通常,任何使用全局变量或依赖于静态内存内容的函数,线程都不安全。
  • 在单CPU系统上,使用线程解决问题实际上要比使用顺序程序慢

线程操作

线程的执行轨迹与进程类似。线程可在内核模式或用户模式下执行。在用户模式下,线
程在进程的相同地址空间中执行,但每个线程都有自己的执行堆栈。线程是独立的执行单
元,可根据操作系统内核的调度策略,对内核进行系统调用,变为挂起、激活以继续执行
等。为了利用线程的共享地址空间,操作系统内核的调度策略可能会优先选择同一进程中的
线程,而不是不同进程中的线程。截至目前,几乎所有的操作系统都支持POSIXPthread,
定义了一系列标准应用程序编程接口(API)来支持线程编程。下面,我们将讨论和演示
Linux中的Pthread并发编程(Goldt等1995;IBM;Love2005;LinuxManPageProgect
2017)。

线程管理函数

pthread_create(thread, attr, function, arg): create thread
pthread_exit(status)	:	terminate thread
pthread_cancel(thread)	:	cancel thread
pthread_attr_init(attr)	:	initialize thread attributes
pthread_attr_destroy(attr): destroy thread attribute

实践

题目:

用线程计算一各N*N整数矩阵中所有元素的和

过程:

代码:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define N 4
int A[N][N],sum[N];

void *func(void *arg)
{
        int j,row ;
        pthread_t tid = pthread_self();
        row = (int)arg;
        printf("Thread %d [%lu] computes sum of row %d
",row,tid,row);
        for(j=0;j<N; j++)
                sum[row] += A[row][j];
        printf("Thread %d [%lu] done:sum [%d] =%d
",row,tid,row,sum[row]);
        pthread_exit ((void*)0);
}
        int main(int argc, char *argv[])
{
        pthread_t thread[N];
        int i,j,r,total = 0;
        void *status;
        printf("Main: initialize A matrix
");
        for(i=0; i<N;i++){
                sum[i] = 0;
                for(j=0;j<N;j++){
                        A[i][j]=i*N+j+1;
                        printf("%4d ",A[i][j]);
                }
                printf( "
" );
        }
        printf ("Main: create %d threads
",N);
        for(i=0;i<N;i++) {
                pthread_create(&thread[i],NULL,func,(void *)i);
        }
        printf("Main: try to join with thread
");
        for(i=0; i<N; i++) {
                pthread_join(thread[i],&status);
                printf("Main: joined with %d [%lu]: status=%d
",i,thread[i],
                                (int)status);
        }
        printf("Main: compute and print total sum:");
        for(i=0;i<N;i++)
                total += sum[i];
        printf ("tatal = %d
",total );
        pthread_exit(NULL);
}

结果:

问题与解决

问题

怎么检测一个线程是否拥有锁?

解决

在java.lang.Thread中有一个方法叫holdsLock(),它返回true如果当且仅当当前线程拥有某个具体对象的锁。

原文地址:https://www.cnblogs.com/BillGreen/p/15490596.html