开发者

Multi-threading in C not working on single-core processor?

So I jus开发者_运维百科t ran the example from this website and it says the the output should alternate like so:

threadFunc says: processing...
main() is running...
threadFunc says: processing...
main() is running...

However on my machine it produces this:

threadFunc says: processing...
threadFunc says: processing...
main() is running...
main() is running...

Is it because I have a single-core processor that isn't multithreaded?

Note: I'm also getting this warning when compiling: implicit declaration of function ‘usleep’

I'm compiling with gcc like so: gcc new.c -o new -lpthread


You need to comment out line:

pthread_join(pth, NULL /* void ** return value could go here */);

Doing this will make it work as you expect

Whats its doing is making the thread wait till the thread pth is finished before proceeding.


No. The order of the output of two threads that write simultaneously to the same place is not well defined and depends on a lot of factors. The first thread might have started earlier than second and might have completed its work before the second even had the chance to start. Another option is that the output is buffered somehow in the thread and is only flushed after reaching a certain threshold.

All of this has nothing with the fact that your processor is a single core. Multi-threading was working well before multi core processors were conceived.

If you want to interleave the output the way you describe you'll need to use some synchronization mechanism such as a critical section or a mutex.


No, the use of the usleep is not a guaranteed way to reschedule your thread. Not even sched_yield is necessarily going to do anything. If you must have alternating execution, you have to use a condition variable or other signalling mechanism. Note that just using a mutex won't do it either, since it won't necessarily reschedule.


It should still multithread properly; try playing around with the number of loop iterations and/or the time in the usleep() calls. Maybe your scheduler is behaving differently, or the output buffering on your system is different.


What is being done in those threads? A single core CPU should timeshare (swap) the execution of the threads. This depends on your OS and how it's scheduler works (and whether you sleep your thread or not).


Multi-threading isn't directly related to the number of cores on a machine: you can very well implement multi-threading on a single processor.

The output you are seeing is probably just related to how the threads are interleaved by the OS thread/process scheduler ( I didn't follow the link to the site you are referencing ).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜