Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly do threading in C++?

I have a rather large, dynamic sparse matrix object class to write, and I want to make the following happen: one thread to handle placing elements into the matrix, and one to handle reading from the matrix.

The only time when these two would conflict would be when they would both want to access the same row/column at the same time. As such, I've decided that a simple mutex lock for each row/column is sufficient.

Now this is the first time I've actually done threading in C/C++, and I'd like to do it by the books, so to speak. I have two concerns.

  1. How do I spawn these threads? This is a language question more than anything.
  2. How do I implement the locking itself as efficiently as possible? I figure if there is a conflict, then the requesting thread would place itself in line and wait until the resource is freed. However, how do I implement that waking? I can have a loop poll the memory location, but that's not elegant. Ideally, I figure an interrupt based approach would be best.
like image 270
alexgolec Avatar asked Nov 27 '22 05:11

alexgolec


1 Answers

If this is your first time to do multi-threading, use the Boost.Threads library. Its semantics (including synchronization mechanisms) are very straightforward and your implementation will be portable.

http://www.boost.org/doc/libs/1_42_0/doc/html/thread.html

like image 193
Ben Collins Avatar answered Dec 04 '22 03:12

Ben Collins