Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.c++ > #68351
| From | "Chris M. Thomasson" <chris.m.thomasson.1@gmail.com> |
|---|---|
| Newsgroups | comp.lang.c++ |
| Subject | Re: std::thread - DESPERATE NEED HELP!!! |
| Date | 2019-09-11 23:01 -0700 |
| Organization | Aioe.org NNTP Server |
| Message-ID | <qlcn0j$13nd$1@gioia.aioe.org> (permalink) |
| References | <NRaeF.332144$R83.166244@fx23.am4> |
On 9/11/2019 11:16 AM, Szyk Cech wrote:
> Hi all!
>
> [What I want]
> I want write reliable and modern Semaphore class.
> I want write unit test to validate it.
[...]
Here is a _very_ basic, bare bones semaphore:
__________________________
#include <iostream>
#include <mutex>
#include <condition_variable>
// Basic, bare bones C++ Semaphore
struct cpp_sem
{
unsigned int m_count;
std::mutex m_mutex;
std::condition_variable m_cond;
cpp_sem(unsigned int count = 0) : m_count(count)
{
}
void dec() // wait
{
std::unique_lock<std::mutex> lock(m_mutex);
while (m_count == 0) m_cond.wait(lock);
--m_count;
}
void inc() // post
{
{
std::unique_lock<std::mutex> lock(m_mutex);
++m_count;
}
m_cond.notify_one();
}
};
int main() {
std::cout << "p0\n";
{
cpp_sem sem(2);
sem.dec();
sem.dec();
std::cout << " a\n";
sem.inc();
sem.inc();
sem.inc();
std::cout << " b\n";
sem.dec();
sem.dec();
sem.dec();
sem.inc();
sem.dec();
std::cout << " c\n";
// sem.dec(); // uncomment for deadlock!
}
std::cout << "p1\n";
return 0;
}
__________________________
This can be improved upon.
Back to comp.lang.c++ | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
std::thread - DESPERATE NEED HELP!!! Szyk Cech <szykcech@spoko.pl> - 2019-09-11 20:16 +0200
Re: std::thread - DESPERATE NEED HELP!!! "Chris M. Thomasson" <chris.m.thomasson.1@gmail.com> - 2019-09-11 23:01 -0700
Re: std::thread - DESPERATE NEED HELP!!! Ralf Fassel <ralfixx@gmx.de> - 2019-09-12 11:14 +0200
Re: std::thread - DESPERATE NEED HELP!!! "Chris M. Thomasson" <chris.m.thomasson.1@gmail.com> - 2019-09-13 12:53 -0700
Re: std::thread - DESPERATE NEED HELP!!! Pavel <pauldontspamtolk@removeyourself.dontspam.yahoo> - 2019-09-13 23:38 -0400
Re: std::thread - DESPERATE NEED HELP!!! "Chris M. Thomasson" <chris.m.thomasson.1@gmail.com> - 2019-09-13 22:07 -0700
Re: std::thread - DESPERATE NEED HELP!!! "Chris M. Thomasson" <chris.m.thomasson.1@gmail.com> - 2019-09-13 22:17 -0700
Re: std::thread - DESPERATE NEED HELP!!! "Chris M. Thomasson" <chris.m.thomasson.1@gmail.com> - 2019-09-13 23:01 -0700
csiph-web