C语言 多线程可以在单处理器系统上实现吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16116952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can multithreading be implemented on a single processor system?
提问by Ayse
I have always followed the concept that multithreading can only be implemented on multiple processors system where there are more than one processor to be assigned to each thread and each thread can be executed simultaneoulsy. There is no scheduling in this case as each of the thread has separate resources all dedicated to it. But I recenetly read it somewhere that I can do multithreading on single processor system as well. Is it correct? and if yes then what is the difference between single processor and multiple processor systems?
我一直遵循这样的概念,即多线程只能在多处理器系统上实现,其中每个线程分配一个以上的处理器,并且每个线程可以同时执行。在这种情况下没有调度,因为每个线程都有专用于它的单独资源。但是我最近在某个地方读到了它,我也可以在单处理器系统上进行多线程处理。这是正确的吗?如果是,那么单处理器和多处理器系统之间有什么区别?
采纳答案by R.. GitHub STOP HELPING ICE
Of course it can be done on a single-processor system, and in fact it's much easier that way. It works the same way as running multiple processes -- the kernel, via a timer interrupt or other similar mechanism, suspends one, saving its machine state, and replacing that by the previously-saved state of another -- the only difference being that two threads of the same process share the same virtual memory space, making the task-switch much more efficient.
当然,它可以在单处理器系统上完成,而且实际上那样更容易。它的工作方式与运行多个进程的方式相同——内核通过定时器中断或其他类似机制暂停一个进程,保存其机器状态,并用先前保存的另一个状态替换它——唯一的区别是两个同一个进程的线程共享同一个虚拟内存空间,使得任务切换更加高效。
Multi-threading on multi-processor systems is actually much more difficult, since you have issues of simultaneous access to memory from multiple cpus/cores, and all the nasty memory synchronization issues that arise out of that.
多处理器系统上的多线程实际上要困难得多,因为您会遇到从多个 CPU/内核同时访问内存的问题,以及由此产生的所有令人讨厌的内存同步问题。
回答by Barath Ravikumar
I recenetly read it somewhere that I can do multithreading on single processor system as well. Is it correct? and if yes then what is the difference between single processor and multiple processor systems?
我最近在某个地方读到它,我也可以在单处理器系统上进行多线程处理。这是正确的吗?如果是,那么单处理器和多处理器系统之间有什么区别?
Yes you can do multithreading on a single processor system.
是的,您可以在单处理器系统上进行多线程处理。
In multi-processor system , multiple threads execute , simultaneouslyon different cores. Eg- If there are two threads and two cores , then each thread would run on individual core.
在多处理器系统中,多个线程同时在不同的内核上执行。例如-如果有两个线程和两个核心,那么每个线程将在单独的核心上运行。
In a single-processor system, multiple threads execute , one after the other or wait until one thread finishes or is preempted by the OS , depending on the thread priority and the OS policy.But the running threads , gives an illusion that they run simultaneous , relative to the required application response time of the User space application.
在单处理器系统中,根据线程优先级和操作系统策略,多个线程一个接一个地执行或等待一个线程完成或被操作系统抢占。但是正在运行的线程给人一种它们同时运行的错觉,相对于用户空间应用所需的应用响应时间。
Time Comparison(Example):
时间对比(示例):
if two threads take 10us each to execute, then on a 2 processor system , the net time take is 10us
如果两个线程每个执行 10us,那么在 2 个处理器系统上,净时间为 10us
if two threads take 10us each to execute, then on a 1 processor system , the net time take is 20us
如果两个线程每个执行需要 10us,那么在 1 个处理器系统上,净时间为 20us
回答by Jim Mischel
You can have more than four active threads on a quad core system. There isscheduling, unless you can guarantee that processes won't try to create more threads than there are processors.
四核系统上可以有四个以上的活动线程。还有就是调度,除非你能保证进程不会尝试创建多个线程比有处理器。
Yes, you can have multiple threads on a single-core computer.
是的,您可以在单核计算机上拥有多个线程。
The difference between single processor and multi-processor systems is that a multi-processor system can indeed do more than one thing at a time. It can do N things at a time, where N is the number of processor cores. A single-processor core can only do one thing at a time. As WhozCraig said in his comment, it's the difference between actual and perceived concurrency.
单处理器和多处理器系统之间的区别在于多处理器系统一次确实可以做不止一件事情。它一次可以做 N 件事,其中 N 是处理器内核的数量。一个单处理器内核一次只能做一件事。正如 WhozCraig 在他的评论中所说,这是实际并发和感知并发之间的区别。
回答by luser droog
Here's a very simplified example. It's actually a prototype for a program I'm building. It's a implementation of cooperative multitasking in a single thread.
这是一个非常简化的示例。它实际上是我正在构建的程序的原型。它是单线程中协作多任务的实现。
mainsimply sets the quitflag to false, and populates an array of function pointers (the tasks), and then calls loop.
main只需将quit标志设置为 false,并填充一个函数指针数组(任务),然后调用loop.
loopuses setjmpto set a return point for a non-local jump (a jump outof the function back to a previous location in the execution) and then proceeds to call the first task (function).
loop用途setjmp设置退货点的非本地跳转(跳转出功能回到以前的位置,在执行的),然后继续调用第一个任务(功能)。
Each task ends with yield(). That is, none of the task functions actually return. Not only do they not contain a return;statement (which would be fine since they are voidfunctions, ie. procedures), but they wouldn't reach the returneven if it was there because yieldjumps back to the setjmpcall, this time yielding a 1 to the ifstatement in loop. The statement controlled by the ifstatement selects a different task before re-entering the whileloop.
每个任务都以yield(). 也就是说,实际上没有任何任务起作用return。它们不仅不包含return;语句(这很好,因为它们是void函数,即过程),而且return即使它在那里,它们也不会到达,因为yield跳回setjmp调用,这次对if语句产生 1在loop。语句控制的if语句在重新进入while循环之前选择不同的任务。
So each task function runs multiple times, yielding to the dispatcher(the if(setjmp...statement) which selects a new task to run.
所以每个任务函数都会运行多次,让给调度程序(if(setjmp...语句),它选择一个新任务来运行。
#include <stdio.h>
#include <setjmp.h>
jmp_buf dispatch;
int ntasks;
void (*task[10])(void);
int quit;
void yield(void) {
longjmp(dispatch, 1);
}
void loop() {
static int i = 0;
if(setjmp(dispatch))
i = (i+1) % ntasks;
while(!quit)
task[i]();
}
int acc = 0;
void a(void) {
if (acc > 10) quit = 1;
printf("A\n");
yield();
}
void b(void) {
acc *= 2;
printf("B\n");
yield();
}
void c(void) {
acc += 1;
printf("C\n");
yield();
}
int main() {
quit = 0;
ntasks = 3;
task[0] = a;
task[1] = b;
task[2] = c;
loop();
return 0;
}
The difference between this example and a single-processor multitasking computer system is the real processor supports interrupting a task in the middle of execution and resuming it later from the same spot. This isn't really possible in a C simulation with tasks as single functions. However, the tasks could be composed of a sequence of C functions which each yield to the dispatcher (an array of function pointers, maybe, or a linked-list).
此示例与单处理器多任务计算机系统之间的区别在于,真正的处理器支持在执行过程中中断任务并稍后从同一位置恢复。这在将任务作为单个函数的 C 模拟中是不可能的。然而,任务可以由一系列 C 函数组成,每个函数都交给调度程序(一个函数指针数组,也许,或者一个链表)。
回答by Christopher
Yes, you totally can. Ages ago (Win 95?) we went from Cooperative Multitasking to Multithreading, because someone always screwed up the cooperative part. Every programm on your computer has at least one thread. Possibly more. And the CPU keep just switching between those all those threads like mad a few million times per second. If none of them has anything to do, it might even go idle for some time.
是的,你完全可以。很久以前(Win 95?)我们从协作多任务到多线程,因为总是有人把协作部分搞砸了。您计算机上的每个程序都至少有一个线程。可能更多。并且 CPU 保持在所有这些线程之间每秒疯狂地切换几百万次。如果他们都无事可做,它甚至可能会闲置一段时间。
Multicore systems only mean that two or more of those threads might run in paralell.
多核系统仅意味着其中两个或多个线程可能并行运行。
However, it brings you a lot less to do so. All you can do with Multithreading on a Single Core machine is simulate Multitasking.
但是,这样做会让您少很多。在单核机器上使用多线程所能做的就是模拟多任务。
Mulitasking is enough to prevent the GUI thread from locking up because of a longrunning operation. However it is generally complicated to implement, unless you have some help from the Compiler or Langauge (like C# async...await). As a result, many GUI programmer just used Multithreading and Invoking to fake multitasking. If that code runs on single or multiple core does not mater for this.
多任务足以防止 GUI 线程因长时间运行而锁定。然而,实现起来通常很复杂,除非您从编译器或语言(如 C# async...await)获得一些帮助。结果,许多 GUI 程序员只是使用多线程和调用来伪造多任务。如果该代码在单核或多核上运行,则无关紧要。
Most importantly, Multitasking is NOT suited for CPU bound operations. But 95% of all Async problems are not CPU bound. They are Network or Disk Bound. On a singlecore computer, Multithreading also does not help with CPU bound stuff. If you got two threads that both need 100% CPU time (same programm or different one) but only one core to run them on, the CPU will just have to switch between running both at 49% and use the remaining 2% for all those other threads that only do a little bit.
最重要的是,多任务不适合 CPU 密集型操作。但是 95% 的异步问题都不是 CPU 限制的。它们是网络或磁盘绑定。在单核计算机上,多线程也无助于处理 CPU 密集型的东西。如果你有两个线程都需要 100% 的 CPU 时间(相同的程序或不同的程序)但只有一个内核来运行它们,那么 CPU 将只需要在两者都以 49% 的速度运行之间切换,并将剩余的 2% 用于所有这些其他线程只做一点点。
Finally only very few problems can actually be Multithreaded. Just try to multithread the Fibonacci Sequence (one thread for each pair) without making it slower, more memory demanding and more complex.
最后只有很少的问题可以被多线程处理。只需尝试对斐波那契数列进行多线程(每对一个线程),而不会使其变慢、内存要求更高且更复杂。
tl;dr; You need Multithreading and a Multicore computer for CPU bound problems. Most async problems are not CPU bound. Multitasking is way enough. And you can totally multitask using threads, even on a single core machine.
tl;博士; 您需要多线程和多核计算机来解决 CPU 限制问题。大多数异步问题不受 CPU 限制。多任务处理就足够了。而且您可以使用线程完全多任务处理,即使在单核机器上也是如此。

