views:

183

answers:

6

So I just 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

A: 

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 ).

jldupont
A: 

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.

Carl Norum
A: 

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).

CookieOfFortune
+3  A: 

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.

shoosh
I just clicked the link and it worked.
Bob Dylan
+1  A: 

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.

Adam Goode
+2  A: 

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.

James Raybould
It will not necessarily work as expected, though it is much more likely to.
Adam Goode