Week 17 Day 1 - Threads and Sockets Programming

Channel:
Subscribers:
2,640
Published on ● Video Link: https://www.youtube.com/watch?v=TCFvovJ6szg



Duration: 1:28:36
156 views
1


Today we talked about two important topics:
1) Multithreading - the ability to run multiple functions at the same time
2) Sockets programming - the ability to read and write data over the Internet


To make a thread in C++, you use the thread class, and pass it a function you want it to run in its own flow of execution:
thread bob(foo,42);


This will make a thread named bob, and when it starts up, it will execute the function foo() and pass to foo the value 42.


If you want to wait until bob finishes (you don't have to, you can detach() a thread as well), you can do this:
bob.join();


Usually, this is about all you need to do, but if you are going to have multiple threads reading and writing to the same variables, then things get dicey. If you're not careful, you can get inconsistent and incorrect results.


To solve this, we usually use "mutex" (mutual exclusion) that allows only one thread at a time into a protected block of code or access to a variable. See the video for details.


Sometimes, you can use an even faster approach called "atomics" which allow you to do math in a thread-safe fashion without needing to slow down for a mutex. Again, see the video on how that works.


For sockets programming, we went over it in both C++ (briefly) and in Java (mainly), with Java preferred since it is a much nicer interface. Essentially, a "socket" is called that since it works like how a power socket works - electricity comes out of the socket and you don't worry about how the power got there: it just did. So when you set up a socket, you don't need to worry about all the intricacies of networking, you just:
1) On the server, open up a port (the port must be an int above 1023). The server will accept connections on that port, and then read and write to them like it reads and writes to standard input/output.
2) On the client, a Socket connects to an IP address (like "www.google.com" or "localhost" which is the current machine) and a port number. Once the connection is established, you can read and write to it as easily as you read and write to standard input and output.


Doing sockets programming in C++ is annoying, since the C++ standard library lacks any conception of networking. You have to use the C standard library to do networking, and it is OLD - dating to when the internet was called "ARPAnet". For this reason, many non-standard libraries exist to do networking in C++, with Boost ASIO and ZMQ being the most popular alternatives.







Tags:
csci 41
thread
threads
mutexes
mutex
sockets
socket
programming