What is threading?
Consider a function that contains an infinite loop:
void* a(void* data)
{
for ( ; ; ) {
printf("a");
}
return NULL;
}
Calling the function
a();
would cause the program to print "a" forever.
Now consider another function with an infinite loop:
void* b(void* data)
{
for ( ; ; ) {
printf("b");
}
return NULL;
}
Calling the function
b();
, it would cause the program to print "b" forever.
What if we were to consecutively call
a(); b();
? Well, since
a()
contains an infinite loop, the call to
b()
is never going to happen, so all we're going to get is "aaaaaaaaaaaaaaaa". Similarly, if we were to call
b(); a();
all we're going to get is "bbbbbbbbbbbbbbbbb". Is there a way to make the program print a little bit of "a" and a little bit of "b" (i.e. "aaaabbbbbbbaaabbbb") without changing the code (i.e. with infinite loops)? This is what threads are about. By creating threads, we make it possible for multiple infinite loops to execute concurrently. Note that there is a slight difference between
concurrency and
parallelism. Parallel execution means two tasks are running completely simultaneously. Concurrent execution means two tasks are switching turns: task 1 is executing, then task 2, then task 1 again... If context switching is happening fast enough (the OS scheduler is the one deciding this), it would appear as if though they were running in parallel. Most synchronization techniques work the same for both so we'll make no distinction.
By default, every program is single-threaded and the only thread running is the one executing the
main()
function. We can create more threads by calling
pthread_create()
and passing the pointer to a callback function (
void* (*cb)(void*);
). If we create two threads - one for function
a()
and one for function
b()
- we will end up
Post too long. Click here to view the full text.