Concurrency in Operating Systems
Transcript
>>Hey everybody. With this lecture, we are going to talk about concurrency in regards to the programs and processes that we are writing and running. So concurrency is kind of an informal term. Let me turn on my laser here. There we go. So the concurrency, as a term, means doing multiple things at the same time. For us, that means decomposing our program into order-independent chunks. So can we create different parts of our program that run and do things where the order doesn't matter, or rather, can run at the same time, but don't interfere with each other. On UNIX, concurrency is easy, so multiple processes
can be running simultaneously, there's no problem with that. Multiple copies of the same program can be running. The CPU time can be split and shared amongst all the various processes that are running. Concurrency is very powerful. It is going to greatly increase the efficiency of that operating system. So while one of those processes is just waiting for input or output or anything else, some other process can use the CPU. The CPU can share its time, can share its available horsepower with whatever processes need to run at any given moment.
Let's look at a couple of definitions here for some of the important terms that we'll be using. A system call versus a library function. A system call is a request for service that your process, your program that you have written that's been loaded into memory and is running as a process, that system call interrupts the flow of that particular process and passes control to the operating system. Typically what that means is that your process is now what we call blocked. It won't do anything else until the system call returns, it's completely stalled at that line and it won't go any further.
Typical cases would be read or write, where basically the process is saying, 'Hey, I gotta get data off the hard drive,' or 'I need to write data to this DVD player,' or something. 'I have to go do something,' that's not something the process can control, so the process blocks and the operating system takes over. A C library function, on the other hand, doesn't have permissions issues, it won't block, these are things like get the square root of something or print out data in a formatted manner. So two different types of things that both look like functions in terms of C.
There are some illusions of simultaneous execution here. Let's talk about the different ways that we can create the illusion of it. So multiprogramming as a term means that more than one process can be ready to execute. The system is going to trigger context switches between the system calls, which let the next process run. So a context switch is going to be switching from one process to another process. This multiprogramming approach allows each process
to basically hand off time between themselves. The process won't be able to execute again until that system call returns. Timesharing is where the CPU time is split between the multiple processes, so it gives the illusion that many processes are running at once. Multiprogramming, there may be various times when a process can hand off its control and it can say, 'I can't do anything else because I am blocked 'in an input, output operation, so somebody else should run,' so another one will switch in, whereas timesharing says that the CPU splits the time no matter what those processes are doing and just splits it up. 'You get ten milliseconds, you get ten milliseconds, you get ten microseconds,' whatever it is, and it fakes the user into thinking that lots of things are running. The processes can also talk to themselves and talk with their companion processes and we'll talk more about that later.
Multiprocessing, on the other hand, as a contrast to multiprogramming, means that were executing multiple processes at the same time. Today's CPUs make that fairly easy. We've got four 10 cores on the CPUs these days and each one acts like a little mini CPU. It can run a particular line of processing from a program at any time. Each one of these cores can be multiprogrammed and each one can timeshare. There's even some fancy things that allow this hyper-threading technology
to fake even a couple more processes per core. So we can do a lot of things at the same time nowadays, where in the old days, we used to think of a CPU like the old Pentiums and the Pentium IIs that can only run one thing at a time and timesharing and multiprocessing is all we had. And we liked it. Alright, possible complications, so some of the concurrently running processes can share data or resources. That might not be something we want. If we have a security consideration, if we have special data in one process, we might not want another process to be able to access that. That could be troublesome. Sometimes we can generate race conditions where more than one thing is trying to access the same resource at the same time. That can cause actual damage. The classic example here would be the ATMs where somebody is trying to withdraw 20 bucks from the same account at the same time from Los Angeles and from New York.
Typical process here, we're going to read whatever the balance is, put it into memory, and then once it's in memory, we can subtract 20 bucks from it and then we can write the new balance back to the bank account. Process 1 is going to read that balance in, 100 bucks, and at the same time, process 2 reads the same balance in. Process 1 subtracts 20 and writes it back. ATM 2 subtracts 20, writes it back, so you've just made 20 bucks, right? You pulled 40, made 20 that wasn't there.
Why are these race conditions so hard to detect? In one sense, there might be only a very special set of circumstances that has to occur for that race condition to rear its ugly head. You may not see that race condition very often because the programmers have tested what they thought was all the possible situations where something could go wrong. Another way of saying this is that, this is the Wikipedia definition, "A race hazard, or a race condition, "is a flaw in a system or process "where the output exhibits unexpected critical dependence "on the relative timing of events." It's something you did not expect, that would be a race condition.
Like I said, that might only ever show up once and it might be a particularly strange set of conditions that causes it. One of the most infamous race conditions was caused by the Therac-25. It was a radiation machine that was used in cancer therapy. One of the problems was that people could outrun the system. So the system was counting on people being slow in terms of typing in the information that the computer attached to the Therac-25 required in order to tell it what to do. But they didn't take into account that people, as they learned, were getting faster and faster and faster with the system and it would skip over errors that would appear on the screen that they didn't know anything about.
Because of this, because the designers for this machine had removed all of the hardware interlocks on it and had made them be only software interlocks, three people ended up dying and three others were seriously injured because of this. It ranks as one of the worst software engineering disasters of all time. A machine that was supposed to be helping people ended up directly killing them. So the lesson here is we have to provide access control. If we have some sort of update situation where there's gonna be concurrency involved, where there might be more than one process accessing the resource at the same time and we've got a situation where at least one of those processes might write to that resource, then we have to provide some form of access control. So if one process is writing, no other process should access it, either for reading or writing, until that write is complete.
A lock is gonna solve that problem, kind of a general term for it. Only the process that owns the lock, only the process that put the lock there, can access for reading and writing the resource. There's lots of different ways to do locking, we'll talk about a few here. Usually there's some sort of support required from the operating system, whether it's just the inclusion of the various libraries or maybe there's a hardware component to it, but you can certainly do it in software also. Access control with a lock file, this is just some generic C code that talks about how we could open up a file. Some sort of loop that might be running, trying to gain a lock, we're gonna say, 'Let's open up some path out to a lock file 'that everybody knows and I want to make sure 'that I only need to be able to write to this particular 'lock file and I want you to be able to create it 'and fail if you're unable to create it, 'or fail if it already exists.'
We'll talk about these flags for open in a later lecture. If there was some horrible problem, then bail out. Otherwise, if the lock already exists, then we know that some other process has already locked that file. So go ahead and go to sleep for a second here in our little demo code, and then try again on the next iteration through the loop. Otherwise, if there was some really bad error, then you know, bail out of the whole thing and break our function here. This is just a simple kind of system that says, 'Try to open up a file that we're gonna define its path 'and if you can, if you can open that up, 'then assume that we can move forward and do whatever we want.'
So a couple other definitions we're gonna need as we talk about concurrency here. The kernel. The kernel is a word we throw around a lot and it kind of refers to just the central part of the operating system. It's where the fundamental routines, the built-in programs, the various hardware abstraction layers that allow the operating system to talk through the drivers to the hardware, it's where that all lives. It fundamentally provides something called the scheduler, that's one of the kernel's primary duties. You don't interact with the kernel by yourself. System calls are requests that are made to the kernel to go do something on your behalf. Our scheduler is going to distribute our prioritized or our fair CPU time based on whatever priorities and how the scheduler has been programmed.
From a process level, we can take a look at our concurrency here. We can imagine that we've got a chat server that needs to watch for users that might be connecting. Maybe it needs to send chat output to all the users and it has to receive chat input from the individual users. But a single process can only do one of these things at a time. We want some sort of concurrency to keep this live system running. So a thread is a way to handle the concurrency that we need. The scheduler can control which of these different processes are running at any given time in order to keep the program running. A thread is a way to organize a particular line of execution that needs to run. So we might split the users into its own thread and output and input into their own threads. They allow the process to do all these things at the same time.
Some advantages of these threads over the processes. Communication between threads is a lot simpler than if we're trying to do interprocess communication, or IPC. So threads share their code, so the threads can see their own program code because they're in the same program, they're written in the same program. Threads share the heap, so they can see the memory that's been created there, and they share data, which means they can see global variables, they can see the initialized and uninitialized global variables, they can see the statics, they can see all that stuff. They each have their own Stack and that makes sense because they have to be able to track
where the function return pointers are and their own automatic variables as they process through their own code, but they can access the Stacks of the other threads. The memory, the particular automatic variables that you're thread is running on, can be accessed by the other threads. They can see what each other is doing. The CPU then, using that scheduler, will switch between the executing threads much faster than if it was gonna switch between the processes. That happens because all that data that we described above is being shared. It doesn't have to be unloaded and loaded back in because of some context switch, all that memory can stay in place. It's merely changing which particular bit of the program is running at any given moment. Each thread can be loaded independently into the system
so that on, say a multi-core CPU, the CPUs can actually run each of these kernel-level threads on a separate core, which gives us actual, true concurrence. We really are running the threads at the same time on different cores. The process can contain multiple threads, and each thread gets its own CPU to run on. The difference between kernel threads and user threads we will talk about in a moment. So some thread disadvantages. What are some thing we don't like about threads?
If there's a race condition that is possible, it's gonna occur. The murphy's law kicks into high gear here and if you really are accessing these shared resources, you're gonna cause problems. So you have to be able to manage that. There could be resource contentions, so if one process is accessing a file, you're not going to be able to access the same file at the same time. Those system calls will block you out. Like we talked about, if there is sensitive data in one thread, say a database has something open, since everything is shared between threads, maybe you don't want all those social security numbers shared from the security thread to the user authentication thread.
Alright, so talk about the two primary types of threads that we'll encounter. Kernel and user-level. The kernel ones are controlled by the kernel and they are given time by the scheduler. They're like mini-processes. These are the ones you typically think of when you say threads. I've got a program that I've written, but when my program starts, it's gonna split itself up into lots of different processes, and all those various processes, all those various little threads are gonna run on their own CPUs and run at the same time. That's what we usually think of, kernel-level threads. These user-level threads are a different beast. The kernel doesn't know about these. They are specifically inside the process itself, so they don't involve the scheduler at all. Switching between these things is done cooperatively- it has to do with when the program wants to do something different.
So you can imagine a program that would maybe process a file for a bit and then you're program would stop doing that and it would switch to reading from a different file, and then it would stop doing that and it would switch back to some other function. From the kernel's perspective, it doesn't care what you're program is doing, it just sees a process that's running. But from your perspective, maybe you are switching between different lines of execution with these user-level threads that you've defined for some particular purpose. Really the primary use for these is in some sort of recursion system where there's some special objective that you have in mind and it can only be solved with a heavily recursed system. User-level threads are about the only way to, well they're one of the ways, to massively parallel such a system, but really for the most part, you don't see them. Sometimes we call them green threads because they don't occupy time on the kernel by themselves. These are pretty rare.
The kernel-level threads get controlled by the kernel. Like we said, they're given time by the scheduler. They're easy to create with built-in libraries in UNIX. In fact, we'll take a look at that in a minute. They're pretty much the better choice in all circumstances. The user-level threads, switching between user-level threads is even faster than switching between kernel threads because you're not even really switching at all. You're just telling one particular part of your program to run and then maybe going to a different other part of your program. It's almost like switching between different function calls inside your program.
One major disadvantage is that the entire program that contains of all these user-level threads, the entire thing can be pre-empted by the scheduler. Maybe some other process has to run on that CPU, so the entire program can be unloaded, the entire process can get unloaded. So blocking system call that happens on your process can also block the entire process. You don't get to separate it out into separate little threads. They're much more difficult to use and the libraries are not built-in to UNIX for doing these.
Alright, so within UNIX, the typical one is a POSIX thread. POSIX is kind of a consortium, a standard way of having various UNIX-like operating systems interact with each other to have the same interfaces. The POSIX threads API is the classic, the most standard way for writing a multi-threaded application on UNIX. It's fairly simple. You can include that pthread.h library header file and that'll give you all the code that you need, and then you need to add this pthread option in gcc and you have to put the little -l with no space attached to it in order to get it to compile. That's what links in all of the code, all of the functions that are defined elsewhere.
So to create a thread, here's some C code for doing this, we would use the pthread create function. The pthread create function has four different arguments to it. Let's just talk about those really briefly. The first one is going to be the variable in which the ID of the new thread gets written into. Thread IDs, you're used to thinking of these threads as- We're used to thinking about IDs as things that occupy just an integer as a way to store them, but often there's actually a whole struct that's involved in storing the ID for a thread. They're not really human-readable. They don't contain data that's something you can just output to see in a nice, easy way. We have some different ways to compare different IDs and we'll talk about that in a bit here. The attribute argument, it points to this particular struct type
that contains option flags if you have any, and normally we don't. This is a very important argument. This is the start_routine, it's a function pointer, which points to the function that is going to be the starting place for the new thread. When that new thread wakes up, it will begin running at start_routine. It's almost like your program gets cloned and the new thread starts running at wherever you tell, whichever function you tell it to start running at. It's kind of like fork, if you're familiar with that, and we'll talk about that more in a later lecture in block three.
The arg, finally the arg one, is if you want to pass in arguments to that start_routine, if you have some integers or whatnot that you want to pass in, that's how you would do it. It's only a single argument, so if you want to pass multiple things in, you have to build a struct up to get it in. Alright, so an example here. Here is a call of pthread_create, note that I've defined an integer for result of the pthread_create function, and then I have a variable that can store the identity of the ID of the thread. So we pass in a pointer to our ID variable. No options, no arguments, and we give it the name of the start_routine that we're going to run. So in this case, I used a function called start_routine. Note that you don't have to put the parentheses there,
that's an interesting part of function pointers, and we'll talk more about function pointers later, but essentially you can pass around the name of a function and use that in some interesting ways. One of those is in the pthread_create function. This will create the thread. To destroy a thread, we can use the pthread_exit function. This is the thread itself saying, 'Alright I'm done. 'Wherever I am, I'm gonna stop running'. So four different ways to kill a thread, the easy one is the thread just kills itself off wherever it wants. The second one is that the thread finishes. So if it reaches the bottom of its routine, of the function that it was told to start on, if it exits off the bottom of that, that's it, it's all done.
Of course you can prevent the thread from exiting that way by putting it in some sort of a loop, you know, some sort of a server process, but the thread otherwise will exit if it actually falls off the end of its program. A thread can also be killed externally by another thread, and that could be the pthread_cancel function. Finally, if any thread in the whole process calls exit, which kills the entire process, then all of the threads die at the same time. Alright, so how can we identify the executing thread? How can we actually tell which thread we have? So you can get your own ID, our process can get its own thread ID by using the pthread_self function. It returns again a struct, normally, and you give it some sort of name. Here I've gotten my own ID and then I can test that ID against some other thread ID. I can say, you know, 'Is this particular thread Thread A 'that I've previously seen 'or is it Thread B that I've previously seen.'
These are the functions that you'll need to be able to figure out which is which. Let's go through an example now here, we've got a three page example of a basic, simple little thread program. We've got a ton of different headers that we've included here, standard libraries, input output functions, the thread library itself, and the assert function which will help us track what we're doing. It'll help us make sure we're doing the right thing. We'll define number of threads as five. This is a C construct that lets us say, 'I'm basically creating a constant integer here,
'wherever you see num_threads, replace it with five'. This runs in the preprocessor. From the perspective of the compiler, it looks like that our program is going to be filled with fives, it never actually sees num_threads. Here we're going to define a function. This function is called perform_work and note that its return type is void*. So it's a void pointer, and that means that it can basically return anything and it's up to the user of this function to figure out what it's supposed to be.
And then the argument that it receives is again a void pointer, and we'll call it argument, and again, it could take anything, so it's up to us to define what that is. So we'll define an integer which will be the passed in value. So here I'm saying right off the bat, 'You know what, 'I'm gonna expect that passed value to be an integer. 'It doesn't have to be, but that's what I'm gonna do.' Then for that passed in value, let's go ahead and assign the argument that we received into that integer value that we have. This is just a raw integer, but look at all the syntax and pointer magic that's required to process a raw integer. The first part here is gonna cast this argument, which started as a pointer, a void pointer, we're gonna cast it as an int pointer. So let's pretend this thing's an int pointer and then dereference it, which gets us the actual integer from this thing, and then store that in here. When we see this printf down here,
this particular function perform_work is gonna say, 'Hello World! It's me, I am the thread with argument,' and then whatever number was passed in. So this thing's gonna report some number. Whatever number it gets, this function simply returns that number. Okay, so here's page two. In this one, we are going to define our main function and it'll return something, and this particular main function is going to define some threads, and these are the indexes for those threads and here we're going to do for num_threads, worth of threads, and we know that's gonna be five, some arguments that we're going to be passing in, again we need five of those, and some result and index codes. Right off the bat, the index is gonna be set up as equal to zero,
and we'll do that less than, or as long as index is less than num_threads, lets run a for loop. So this is gonna be five different instances, right? Zero one two three four. Five different times, and we'll increment index each time. What our for loop here does is it's gonna create the threads one by one. First of all, our arguments, let's go ahead and say that for wherever we are, argument zero, or for index zero, let's go ahead and make the argument be zero. So the first argument for the first thread will be zero, the second one will be one, the third one will be two, and on up. And we'll print out that we're in main and that we're creating that thread. Go ahead and indicate which thread we're creating as we go. Then actually create the thread. Here's that result code and we want to make sure
that has a value that's not, you know, death, we want to make sure that's a successful thing. We pass in our arguments here. So we pass in a particular ID that will be written back into this particular array. No options for this thing. Here's where we want it to start, so we want this thread to start in the perform_work function that we previously defined. Then the arguments list that we're gonna be passing in is basically just that integer. So here is the address to the thread_args array, and we pass in which particular one? It's whatever the index that we're currently on is. Note that we have to cast it to a void* because that's what's expected by the function. Assert 0 equals result_code. This little function here is gonna verify that our result code actually gave us zero. So if it didn't, if this wasn't the case, then assert would fail and the program would stop, but you could write this as basically as an if statement. You could say if result_code is equal to zero, then die,
but assert is kind of just a faster way to do it, a little bit of a fancier way to do it. Alright, so down here let's look at what happens with our thread example here. So we're going to wait for each thread to complete. Once it's created all of them, we're then gonna start up this for loop. What this for loop is gonna do is it's gonna again start with index at zero and it's gonna go up to the number of threads, so run five times, and it's gonna check the result_code of running the join function, which we haven't talked about. Join is a critical function in terms of making all of these various threads work together. What it does is it says, 'Alright, so my main process 'that's running here, which is its own thread, I want this one
'to block and do nothing else until this thread completes.' So remember, threads index, that is the actual IDs of our threads. Here's the previous page, so this function says, 'Alright, block my main process here, my main thread, 'block this thing until this particular index stops, 'until this particular thread terminates. 'When that happens, continue and then print out 'that that thread is completed and do this for all five threads'. So they're going to complete in different orders and obviously this thing is going to start with the first one and then proceed through the fifth, so we'll see them expire in that order. If this thing was running with some sort of loop where it just skipped over it if one hasn't died, then we'd see them be in random orders, but we're dictating the order that's gonna happen here. And then again, assert for our result code.
And then finally printf that we're all done, that all threads are completed, and then exit with some sort of EXIT_SUCCESS. Now one interesting note here, I have left this bug in here so that you could see the difference. Note that our main function is supposed to return an int when it completes. But here we didn't use the return function, we didn't use the little return keyword. That means that the return value won't be given back to the operating system via the return mechanism.
Instead, what exit does is it kills the process where it stands and then gives this exit success, which is zero, it gives that to the operating system as the return result of this particular program. So this is bad style, so you should not be ending your programs with exit. It's kinda harsh. You want to return from main, if at all possible. Exit is great for something that's inside in the middle of a program, but it's not great for something that's just at the end of your program.
Alright, so let's take a look at the results that we have for this particular process. The results that we have here, first of all let's compile this thing. Here's our threadtest.c file that we've written everything in. We're gonna output this thing as threadtest, that's the name of the program, and we have to include the pthread library for linking purposes, and that will compile it. And note no results, so that's good, nothing weird happened. And so that funny business with the warning and the exit, we don't actually get any error results as part of that, so that's intriguing. So then we run the threadtest.
What threadtest does is it says right off the bat, 'We create threads 0, 1, and 2, 'and then the threads start reporting in.' The order for these is dictated by the operating system, by whatever state it happens to be in. So we see that Hello World! thread 0 reports that it's alive and that it exists before thread 3 is created because these things are all running concurrently at the same time. And then we see 1 and 2, then thread 4 is created, which is our last one.
And then here's the "Hello World! It's me," thread with argument 3. Then they start to complete, even before the last one has reported in. And again, they complete in order, as we talked about before. And then finally, the main thread wakes back up and says, 'All the threads have completed successfully, after all those pthread join functions have finished. So there's a very nice little program that is a great template for running our multi-threaded application. Okay, so another topic that we're going to talk about here today is going to be mutexes.
The mutexes, this is kind of the last subject here, but mutexes are an abbreviation for mutual exclusion. They are again apart of the POSIX pthread API and they allow you to provide some form of thread synchronization using a lock. So we talked about file locks before, mutexes are like variable locks and they allow you to protect data or protect resources however you want. They're up to you to implement the actual usage of them. This is like giving you a box full of padlocks and saying to go to town. It's up to you to actually put them in the right place. So there's a bunch of different types of these things, which you're gonna check for errors and go faster and all that, but we'll just show kind of the standard way these work.
Okay, the life span of a mutex. The lifespan of this thing begins when you have one defined. So here I have one defined called myMutex and it's of type pthread_mutex_t. And this thing is born basically by using this funny, funny macro here, this funny- This element that's defined called PTHREAD_MUTEX_INITIALIZER. That fires this thing up and makes it be something that's accessible now. You can kill it off with a destroy function, and why this is, I'm not sure.
Something deep within the API I'm sure for why this isn't a function and I'm sure there isn't a reason they couldn't wrap a function around it, but they just haven't. So the destroy is its own function. To lock these things, a thread is gonna acquire that lock on a mutex variable and it's gonna grab that lock by calling the lock function. So here we initialized the mutex to start it running, and then we lock it by saying pthread_mutex_lock, and then you pass in the variable itself. Once that mutex is locked, any other thread, or any other attempt even from the same thread, that attempts to lock that, it will block. Any other thread will block and not run any further if they try to lock something that's already locked. Picture that as like if there is a treasure chest and it's already got a padlock on it. If you walk up to it and put your own padlock on it, you're not going anywhere either. You're padlock is gonna block you there because there's already one on there.
So to unlock it, then the thread that had previously locked that variable, this mutex variable, calls the unlock function, and just like that, that's it. Then the lock is removed for that mutex and that variable then becomes available for something else to then lock it later. However, if there were other threads, or if there were other instances of lock functions that had been run on that mutex, then essentially one of those gets chosen randomly, gets to become the one that gets to unblock and begin running again. If thread A is running and thread B is running, and if thread A calls lock on a mutex first and then thread B calls lock on that mutex again, then thread B is blocked while thread A can continue on. As soon as thread A calls unlock, thread B immediately starts running again. So there is a non-blocking way you can try to lock these things and it's basically a way to say, 'Hey, is there a lock on that particular mutex already?'
It's called the trylock function. Trylock will basically give you some result that can tell you yes or no. Somebody has a lock or somebody doesn't have a lock on it. So mutex is a form of a semaphore. It's a specific form of something called a semaphore. There are a couple different flavors of the semaphores. A counting semaphore is one where there's some sort of resource count, like the slide here says, the number of available buffers or maybe it's the number
of files we have open at once or maybe it's the number of connections that are established. So we have some sort of semaphore, some flag, is another name for these things, that is counting upwards and counting down when things happen. A binary semaphore is one that exists between just the two states, so in our case it'd be locked or unlocked for that mutex. These things were invented by a fellow named Edsger Dijkstra who was Dutch and somewhere around '62 or '63. So these things are pretty old. We've had the concept of semaphores and mutexes for a long time. The usage of these, we really see in modern multi-threaded applications on multicore, multiprocessing systems. We finally see the realization of high speed parallel programming today. So we'll talk more about Dijkstra later. I hope you learned all about concurrency of the UNIX system from this lecture, I hope it was enjoyable, and we will see you next time. Thanks. [END]

Ask anything
We've read this whole study set, so questions about it get the best answers.