quartz/content/notes/18-processes-sharing-and-threads.md
2022-10-12 11:44:45 +13:00

2.7 KiB
Raw Blame History

title aliases tags sr-due sr-interval sr-ease
18-processes-sharing-and-threads
cosc204
lecture
2022-10-15 3 250

Shared memory for processes

linux memory space layout

Can't assume all variables are initally zero. OS decide which process maps who which physical address

memory mapping mmap is a family of system calls:

  • allow two processes to share some region of their memory space.
  • achieved by creating a memory region that can be shared by other processes

map diagram

mmap examples

shared memory by two processes mapping to the same file or using fork() after mmap()

random_fd = open("/home/hzy/test/zero", O_RDWR);
ptr = mmap(NULL, 10240, PROT_READ|PROT_WRITE,
	MAP_SHARED | MAP_FILE, random_fd, 0);

private mapping is often used to set up new memory sections.

fd = open("mmap_test_file", O_RDWR); p
tr = mmap(NULL, 10240, PROT_READ|PROT_WRITE, 
	MAP_PRIVATE|MAP_FILE, fd, 0);

Threads

product consumer problem

  • a producer process writes data to a buffer of fied size
  • a consumer reads data from the buffer these two processes are being scheduled independently by the CPU

producer must wait if buffer is full consumer must wait if buffer is empty

threads

  • allows more convenient data sharing
  • threads within a single process share everything except they have their own program counter, registers and stack space

diagram

why

  • responsiveness - parrallelism - dont have to wait
  • resource sharing - automaticall share everything in same process
  • economy - lightweight, creating and switching between threads is faster than creating heavyweight processes
  • scalability - each to work on multiprocessor architectures

pthread

  • pthread_create(): create a thread
  • pthread_exit(): terminate a thread
  • pthread_join(): wait for a thread to terminate
  • pthread_detach(): detach a thread so that it wont be waited
  • pthread_self(): get the thread id of the current thread
  • pthread_equal(): compare if two threads are the same
  • pthread_cancel(): send a cancellation request to a thread
void *myThreadFun(void *vargp) { 
	sleep(1);
	printf("Hello from Thread \n");
	return NULL;
} 
	
int main() { 
	pthread_t thread_id;
	printf("Before Thread\n");
	pthread_create(&thread_id, NULL, myThreadFun, NULL);
	pthread_join(thread_id, NULL);
	printf("After Thread\n");
	exit(0);
}

web server thread

  • a web server is a process that provides data over the web to requesting clients
  • a thread is created for each request

Lightweight process - shares everything except the stack