CS5600 NOTE 02/11 Thread Thread is different from process, process have own virtual memory, one-to-one relationship. multiple threads can map to same virtual memory, many-to-one relationship. Process needs its own text, data, stack. Each thread has its own stack but share text and data area. Thread stacks area its in different location in master process area. Firefox is multi thread engine. Each chrome background has its own process. The advantage is it will not collapse all if one process is collapse. Threads can communication with each other by writing data on their share data area rather than use pipe to visit kernel. (Process can communicate with pipe). System call clone: clone exist process or thread, create a new task. Can choose whether share the virtual memory. If share virtual memory, it clone thread. if not, it clone process. How to create thread ( c language) int count = 0; //global variable Main(){ pthread_t pth; pthread_create(&pth, NULL, childThread, “A”); void *retval; count = count +1; pthread_join(&pth,&retval)//waiting for thread pth to join printf(“%d”, count); //may print 1 or 2, because thread share the same data memory } void *childThread(void *arg){ count = count+1; return (void*)2; } If something went wrong, the whole process went down. //count = count +1 assembly code mov &count,%eax step 1 add 1,%eax step 2 mov %eax,&count step 3 if thread 1 and thread2 run concurrency , the running step is thread 1 run step1 thread 2 run step1 thread 1 run step2 thread 2 run step2 thread 1 run step3 thread 2 run step3 count result is 1 Another example: critical section int count = 0; //global variable int v= 0; //use for lock and unlock Main(){ pthread_t pth; pthread_create(&pth, NULL, childThread, “A”); void *retval; count = count +1; pthread_join(&pth,&retval)//waiting for thread pth to join printf(“%d”, count); //should print 2, because thread share the same data memory and parent thread wait for child process cann’t access incre method at the same time } void *childThread(void *arg){ count = count+1; return (void*)2; } void incre(){ lock(); //prevent other threads running when current thread running count = count+1; unlock(); //notify other threads can running } void lock(){ while(v==1){ sleep(1); } v = v+1; } void unlock(){ while(v==0){ } v = v-1; } //for two thread lock, have questions, figure out next class int flag[2]; flag[0] = flag[1] = 0; int turn = 0; void lock(){ flag[tid] = 1; turn = 1-tid; while((flag[1-tid] ==1)&&(turn==1-tid)){ }; } two cases 1 Flag[0] 1 Turn 1 2 Flag[1] 1 Turn 0 cmpxchg (int *x, int y, int z){ int ret = *x; if(*x==y) *x = z; return ret; } int l = 0;//global variable lock(){ while(1){ int r = cmpxchg(&l,0,1); if(r==1) break; } }