我最近听过一些人说在Linux中,使用进程而不是线程几乎总是更好,因为Linux在处理进程方面非常有效,并且因为线程有很多问题(例如锁定).但是,我很怀疑,因为在某些情况下,线程似乎可以带来相当大的性能提升.
所以我的问题是,当遇到线程和进程都能很好地处理的情况时,我应该使用进程还是线程?例如,如果我正在编写Web服务器,我应该使用进程或线程(或组合)吗?
我听说在多核服务器在Linux上是不可能达到最佳性能,当你刚刚1的过程,但多线程因为Linux对IO一定的局限性,使1个与工艺8核服务器上8个线程可能慢于8个进程.
任何意见?还有其他限制可能会减慢应用程序的速度吗?这些应用程序是一个网络C++应用程序,为100个客户端提供一些磁盘IO.
更新:我担心除了我自己实现的锁定之外还有一些与IO相关的问题......在几个线程中是否有任何问题在同时进行网络/磁盘IO?
所有,
下面的代码来自"Unix环境中的高级编程",它创建一个新线程,并打印主线程和新线程的进程ID和线程ID.
在本书中,它表示在linux中,此代码的输出将显示两个线程具有不同的进程ID,因为pthread使用轻量级进程来模拟线程.但是当我在Ubuntu 12.04中运行此代码时,它有内核3.2,打印相同的pid.
那么,新的linux内核是否会改变pthread的内部实现?
#include "apue.h"
#include <pthread.h>
pthread_t ntid;
void printids(const char *s) {
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("%s pid %u tid %u (0x%x)\n",
s, (unsigned int)pid, (unsigned int)tid, (unsigned int)tid);
}
void *thread_fn(void* arg) {
printids("new thread: ");
return (void *)0;
}
int main(void) {
int err;
err = pthread_create(&ntid, NULL, thread_fn, NULL);
if (err != 0)
err_quit("can't create thread: %s\n", strerror(err));
printids("main thread: ");
sleep(1);
return 0;
}
Run Code Online (Sandbox Code Playgroud)