Here is my code:
static long x = 0;
void * thread_func(void *arg){
while(1){
printf("Thread 2 says %ld\n",++x);
sleep(1);
}
}
int main(){
pthread_t tid;
pthread_create(&tid,NULL,thread_func,NULL);
while(x < 10) {
printf("Thread 1 says %ld\n",++x);
sleep(2);
}
return 0;
}
Now what shall be the output, the book says it will be:
OUTPUT
Thread 1 says 1
Thread 2 says 2
Thread 2 says 3
Thread 1 says 4
Thread 2 says 5
Thread 2 says 6
Thread 1 says 7
Thread 2 says 8
Thread 2 says 9
Thread 1 says 10
Thread 2 says 11
Thread 2 says 12
Now shall not the first one should be Thread 2 says 1, since the pthread_create() is before the while loop in main.
Also how does sleep work here?
Like what exactly is a thread sleeping for, and what process executes when the executing thread sleeps.?
i.e sleep(1) and sleep(2) what does 1 and 2 signify?
I am not sure what book you are reading, but you should stop reading it immediately. First of all, you cannot guarantee that thread will be up and running before entering a loop in
main. It could start before or after. Second of all, there is no access synchronization when accessing variablexfrom two different threads, thus no guarantee as for what value it will have. Callingprintfsynchronizes onstdoutobject, and callingsleepswaps the thread out, and it takes a lot of time to schedule it again. This example is useless and assumptions about the output are wrong.Now, some answers..
Not necessarily. It takes hell of a lot CPU cycles to start another thread. So it is most likely that you will enter
whileloop inmainbefore that other thread starts. But, not necessarily.It tells the kernel not to execute the calling thread for a given number of seconds. The actual sleeping time could be a bit longer due to overhead associated with scheduling. Other threads are not affected by that (well, they are, but not directly, i.e. other threads can have more CPU time etc.).
Process never executes anything. It is the kernel’s schedule that executes processes (and threads). By default, process consists of one main thread, and kernel executes it. When you create more threads, scheduler executes more threads inside the process etc. When one or more threads are sleeping, schedulers executes those not sleeping. Think of the threads as of processes sharing the same address space – that’s what they are.