Unix Network Programming Assignment-1 Solutions

Winter semester, Department of Computer Science

University of Hyderabad


  1. Which system call is used to implement Native Linux Threads?

A: clone()

  1. Can the priority inversion problem happen with user-level threads? why or why not?

A: A low-priority process is in its critical section and suddenly if a high-priority process becomes ready and is scheduled then it is in busy waiting and the low-priority process never gets the chance to leave its critical section and the high-priority process loops forever. This is called priority inversion problem. In case of user-level threads, it can not happen that a low-priority thread is suddenly preempted allow a high-priority thread run. There is no preemption. With the kernel threads this problem can arise.

Note: For more information about this problem, read the article "What really happened on Mars?" (Use Google).

  1. In a system with threads , is there one stack per thread or one stack per process when user-level threads are used? what about when kernel-level threads are used? Explain.

A: Each thread calls procedures on its own, so it must have its own stack for the local variables and return addresses , and so on. This is equally true for user-level threads as for kernel-level threads.

  1. The following is the program which gives the output as shown in thread1.out.

#include <pthread.h>

#include <stdio.h>

#define NUM_THREADS 8

char *messages[NUM_THREADS];

void *PrintHello(void *threadid)

{

int *id_ptr, taskid;

sleep(1);

id_ptr = (int *) threadid;

taskid = *id_ptr;

printf("Thread %d: %s\n", taskid, messages[taskid]);

pthread_exit(NULL);

}

int main(int argc, char *argv[])

{

pthread_t threads[NUM_THREADS];

int *taskids[NUM_THREADS];

int rc, t;

messages[0] = "Hi"

messages[1] = "Enjoy";

messages[2] = "The";

messages[3] = "Unix";

messages[4] = "Network";

messages[5] = "Programming";

messages[6] = "With";

messages[7] = "GNU/Linux";


for(t=0;t<NUM_THREADS;t++)

{

taskids[t] = (int *) malloc(sizeof(int));

*taskids[t] = t;

printf("Creating thread %d\n", t);

rc = pthread_create(&threads[t], NULL, PrintHello, (void *) taskids[t]);

if (rc)

{

printf("ERROR; return code from pthread_create() is %d\n", rc);

exit(-1);

}

}

pthread_exit(NULL);

}

thread1.out :

Creating thread 0

Creating thread 1

Creating thread 2

Creating thread 3

Creating thread 4

Creating thread 5

Creating thread 6

Creating thread 7

Thread 0: Hi

Thread 1: Enjoy

Thread 2: The

Thread3 : Unix

Thread 4: Network

Thread 5: Programming

Thread 6: With

Thread 7: GNU/Linux