何时选择多线程或多处理? [英] When to choose multithreading or multiprocessing?

查看:381
本文介绍了何时选择多线程或多处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从未在并发编程上做过任何事情,我对它们的了解仅来自OS 图书.

I've never done something on concurrent programming.What I know about them is only from OS books.

我今天在一次采访中遇到了这个问题.我想知道是否有人可以给我一个直观的

And I met this question on an interview today. I wonder if anybody can give me an intuitive

关于多线程和多进程以及何时选择它们的说明.或者,也许可以

explanation on multithread and multiprocess and when to choose them. Or,maybe you can

向我推荐一些书籍或带有实际示例的链接.我想阅读

recommend me some books or links with actual examples. And I want to read source codes of

具有一致编程的开源项目(c/c ++),希望您可以推荐一个.

open-source project(c/c++) with conccurent programming,Hope that you can recommend one .

非常感谢您的帮助.

推荐答案

多线程:

  • 执行在个线程之间进行分配;在某些操作系统上,这些线程比进程轻.相反,在Linux上,它们是使用相同的数据结构在内部实现的.
  • 线程共享内存,因此必须通过互斥机制(例如,信号量,互斥量,条件变量等)保护全局共享数据结构
  • 在Linux上, pthread 库(代表"POSIX线程")在用户级别提供了多线程支持.线程是使用pthread_create()创建的;通过使用 -pthread 选项进行编译,可以将该库用于普通C/C ++程序.
  • Execution is split among threads; on some operating systems these threads are lighter than processes; on Linux, instead, they are internally implemented using the same data structures.
  • Threads share memory, so global shared data structures must be protected through mutual exclusion mechanisms (e.g., semaphores, mutex, condition variables, etc.)
  • On Linux, the pthread library (which stands for "POSIX threads") provides multithread support at user-level; threads are created using pthread_create(); this library can be used in normal C/C++ programs by compiling with the -pthread option.

多进程:

  • 执行在个进程
  • 之间进行分配
  • 传统上,进程不共享内存.但是在Linux上,进程也可以通过适当的系统调用来共享内存
  • 在POSIX系统(例如Linux)上,进程是通过 fork()系统调用创建的:一个进程(称为父")可以创建("fork")另一个进程(称为孩子"). C/C ++程序不需要链接到任何外部库即可调用fork().
  • 通常通过消息传递机制(例如管道,fifo和套接字)交换数据
  • Execution is split among processes
  • Processes traditionally do not share memory; on Linux, however, processes can also share memory through suitable system calls
  • On POSIX systems (e.g., Linux), processes are created through the fork() system call: a process (called "parent") can create ("fork") another process (called "child"). C/C++ program do not need to be linked to any external library to call fork().
  • Data is usually exchanged through message passing mechanisms (e.g., pipes, fifos and sockets)

使用多线程还是多进程的决定通常取决于两个因素:

The decision between using multithread or multiprocess usually depends on two factors:

  1. 如果需要在不同执行实体之间共享数据.消息传递机制不如共享内存快和灵活.因此,在某些情况下,最好使用线程代替进程.
  2. 可靠性:多进程应用程序通常更可靠,因为一个进程的崩溃不会影响其他进程.

最后一点:非常复杂的应用程序可以同时具有多线程多进程,以满足软件特定部分的需求.

A final note: very complex applications can have both multithread and multiprocess to accomplish the needs of particular parts of the software.

这篇关于何时选择多线程或多处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆