mutex with pthread - linux

I need to call a function that returns a unique id,
int getid()
{
static id=0;
id++;
return id;
}
Multiple threads need to call this function, my problem is I'm not sure where I need to lock the mutex,
Do I need to lock before and after calling the function like below
pthread_mutex_lock( &id );
int id = getid()
pthread_mutex_unlock( &id );
can someone help me with that please?

It doesn't really matter where it was locked as long as it was before the access to the shared state. It would be less prone to errors if the mutex locking was inside the function. Something minimal like this would work:
int getid()
{
static int id=0;
pthread_mutex_lock( &mutex );
int newId = ++id;
pthread_mutex_unlock( &mutex );
return newId;
}
There are some issues around the initialization of the static variable being thread safe that you may want to look into.

For a single integer you don't need a full mutex, atomic increment would be enough:
int getid() {
static int id = 0;
return __sync_fetch_and_add( &id, 1 );
}

Related

The difference btween std::atomic and std::mutex

how to use std::atomic<>
In the question above, obviously we can just use std::mutex to keep thread safety. I want to know when to use which one.
classs A
{
std::atomic<int> x;
public:
A()
{
x=0;
}
void Add()
{
x++;
}
void Sub()
{
x--;
}
};
and
std::mutex mtx;
classs A
{
int x;
public:
A()
{
x=0;
}
void Add()
{
std::lock_guard<std::mutex> guard(mtx);
x++;
}
void Sub()
{
std::lock_guard<std::mutex> guard(mtx);
x--;
}
};
As a rule of thumb, use std::atomic for POD types where the underlying specialisation will be able to use something clever like a bus lock on the CPU (which will give you no more overhead than a pipeline dump), or even a spin lock. On some systems, an int might already be atomic, so std::atomic<int> will specialise out effectively to an int.
Use std::mutex for non-POD types, bearing in mind that acquiring a mutex is at least an order of magnitude slower than a bus lock.
If you're still unsure, measure the performance.

Try to compare 2 methods to implement bounded blocking queue

bounded blocking queue is famous, of course. There are mostly 2 methods to implement it. I try to understand which way is better:
Method 1: use counting semaphore
void *producer(void *arg) {
int i;
for (i = 0; i < loops; i++) {
sem_wait(&empty);
sem_wait(&mutex);
put(i);
sem_post(&mutex);
sem_post(&full);
}
}
void *consumer(void *arg) {
int i;
for (i = 0; i < loops; i++) {
sem_wait(&full);
sem_wait(&mutex);
int tmp = get();
sem_post(&mutex);
sem_post(&empty);
printf("%d\n", tmp);
}
}
Method 2: classic monitor pattern
class BoundedBuffer {
private:
int buffer[MAX];
int fill, use;
int fullEntries;
pthread_mutex_t monitor; // monitor lock
pthread_cond_t empty;
pthread_cond_t full;
public:
BoundedBuffer() {
use = fill = fullEntries = 0;
}
void produce(int element) {
pthread_mutex_lock(&monitor);
while (fullEntries == MAX)
pthread_cond_wait(&empty, &monitor);
//do something
pthread_cond_signal(&full);
pthread_mutex_unlock(&monitor);
}
int consume() {
pthread_mutex_lock(&monitor);
while (fullEntries == 0)
pthread_cond_wait(&full, &monitor);
//do something
pthread_cond_signal(&empty);
pthread_mutex_unlock(&monitor);
return tmp;
}
}
I understand the 2nd method can solve a lot of other problems. But how to compare these 2 methods? Looks like they can both fulfill the task.
Is there any link on detailed comparision?
Appreciate your help.
Thanks.
The big difference between those two methods is that the first one does not use pthread_ specific functions (semaphores are not part of pthread) and as such is not guaranteed to work in multithreaded enviornment.
In particular, semaphores do not protect memory ordering, so things written in one thread might not be readable on another. Mutexes are suitable for multi-thread message queue.

Correct interactions between Linux kernel wait-queues and lists

I'm writing a Linux kernel module which involves a list being read/written from different process contexts and feel I'm missing functionality equivalent to pthread_cond_wait() and co. from user-space.
Naively I might write something like this:
static LIST_HEAD(request_list);
static DEFINE_MUTEX(request_list_mutex);
static DECLARE_WAIT_QUEUE_HEAD(request_list_post_wq);
static void post_request(request_t *request)
{
mutex_lock(request_list_mutex);
list_add(request, request_list);
mutex_unlock(request_list_mutex);
wake_event(request_list_post_wq);
}
static void wait_and_consume_request()
{
mutex_lock(request_list_mutex);
if(list_empty(request_list)) {
mutex_unlock(request_list_mutex);
wait_event(request_list_post_wq, !list_empty(request_list));
mutex_lock(request_list_mutex);
}
// do something with request
mutex_unlock(request_list_mutex);
}
However, this looks like it will have a race condition in the consumer function between waking on a non-empty list and then re-acquiring the mutex if there are multiple consumers. At the same time I have to release the mutex before waiting otherwise nothing will ever be able to add to the list.
I considered writing a function which locks the request_list, and only unlocks it if it's still empty and use this as the conditional to wait_event... but googling around I've seen lots of examples of people writing wait_event(...., !list_empty(...)) so I must be missing something?
The helper function that the other person suggested isn't needed at all:
static int list_is_not_empty()
{
int rv = 1;
mutex_lock(request_list_mutex);
rv = !list_empty(request_list);
mutex_unlock(request_list_mutex);
return rv;
}
There's no need to lock the list just to see if it's empty or not. So simply:
static void wait_and_consume_request()
{
wait_event(request_list_post_wq, !list_empty(request_list));
mutex_lock(request_list_mutex);
if(!list_empty(request_list)) {
// do something with request
}
mutex_unlock(request_list_mutex);
}
But this won't guarantee that you actually consume a request. If we do want to ensure that we consume exactly one request, then:
static void wait_and_consume_request()
{
mutex_lock(request_list_mutex);
while(list_empty(request_list)) {
mutex_unlock(request_list_mutex);
wait_event(request_list_post_wq, !list_empty());
lock_mutex();
}
// do something with request
mutex_unlock(request_list_mutex);
}
Here's a real example from the kernel in drivers/misc/carma/carma-fpga.c (I just took the first example that I could see)
spin_lock_irq(&priv->lock);
/* Block until there is at least one buffer on the used list */
while (list_empty(used)) {
spin_unlock_irq(&priv->lock);
if (filp->f_flags & O_NONBLOCK)
return -EAGAIN;
ret = wait_event_interruptible(priv->wait, !list_empty(used));
if (ret)
return ret;
spin_lock_irq(&priv->lock);
}
/* Grab the first buffer off of the used list */
dbuf = list_first_entry(used, struct data_buf, entry);
list_del_init(&dbuf->entry);
spin_unlock_irq(&priv->lock);

memory corruption while executing my code

# include "stdafx.h"
# include <iostream>
#include <ctype.h>
using namespace std;
class a
{
protected:
int d;
public:
virtual void assign(int A) = 0;
int get();
};
class b : a
{
char* n;
public:
b()
{
n=NULL;
}
virtual ~b()
{
delete n;
}
void assign(int A)
{
d=A;
}
void assignchar(char *c)
{
n=c;
}
int get()
{
return d;
}
char* getchart()
{
return n;
}
};
class c : b
{
b *pB;
int e;
public:
c()
{
pB=new b();
}
~c()
{
delete pB;
}
void assign(int A)
{
e=A;
pB->assign(A);
}
int get()
{
return e;
}
b* getp()
{
return pB;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
c *pC=new c();
pC->assign(10);
b *p=pC->getp();
p->assignchar("a");
char *abc=p->getchart();
delete pC;
cout<<*abc<<endl;
getchar();
}
i'm a noob at c++ and was experimenting when i got to this point. I don't understand why i keep getting a memory corruption message from VS2010. I am trying to replicate a problem which is at a higher level by breaking it down into smaller bits, any help would be appreciated.
From a cursory glance, you are passing a static char array to AssignChar that cannot be deleted (ie when you type "A" into your code, its a special block of memory the compiler allocates for you).
You need to understand what assignment of a char* does (or any pointer to type). When you call n=c you are just assigning the pointer, the memory that pointer points to remains where it is. So, unless this is exactly what you meant to do, you will have 2 pointers pointing to the same block of memory.. and you need to decide which to delete (you can't delete it twice, that'd be bad).
My advice here is to start using C++, so no more char* types, use std::string instead. Using char* is C programming. Note that if you did use a std::string, and passed one to assignChars, it would copy as you expected (and there is no need to free std::string objects in your destructor, they handle all that for you).
The problem occurs when you're trying to delete pC.
When ~c() destructor calls ~b() destructor - you're trying to delete n;.
The problem is that after assignchar(), n points to a string literal which was given to it as an argument ("a").
That string is not dynamically allocated, and should not be freed, meaning you should either remove the 'delete n;' line, or give a dynamically-allocated string to assignchar() as an argument.

How to use CriticalSection - MFC?

I' am working on a small example and am a bit of curious using criticalsection in my example.
What I'am doing is,I have a CStringArray(which has 10 elements added to it).I want to copy
these 10 elements(string) to another CStringArray(am doing this to understand threading and Critical section),I have created 2 threads,Thread1 will copy the first 5 element to another CStringArray and Thread2 will copy the rest.Here two CStringArray are being used,I know only 1 thread can access it at a time.I wanted to know how this can be solved by using criticalsection or any other method.
void CThreadingEx4Dlg::OnBnClickedOk()
{
// TODO: Add your control notification handler code here
thread1 = AfxBeginThread((AFX_THREADPROC)MyThreadFunction1,this);
thread2 = AfxBeginThread((AFX_THREADPROC)MyThreadFunction2,this);
}
UINT MyThreadFunction1(LPARAM lparam)
{
CThreadingEx4Dlg* pthis = (CThreadingEx4Dlg*)lparam;
pthis->MyFunction(0,5);
return 0;
}
UINT MyThreadFunction2(LPARAM lparam)
{
CThreadingEx4Dlg* pthis = (CThreadingEx4Dlg*)lparam;
pthis->MyFunction(6,10);
return 0;
}
void CThreadingEx4Dlg::MyFunction(int minCount,int maxCount)
{
for(int i=minCount;i<=maxCount;i++)
{
CString temp;
temp = myArray.GetAt(i);
myShiftArray.Add(temp);
}
}
The way I'd use a CriticalSection is:
Declare a member variable in your CThreadingEx4Dlg class:
CCriticalSection m_CriticalSection;
Enclose your not thread safe code in a Lock-Unlock block of this CriticalSection:
void CThreadingEx4Dlg::MyFunction(int minCount,int maxCount)
{
m_CriticalSection.Lock();
for(int i=minCount;i<=maxCount;i++)
myShiftArray.Add(myArray.GetAt(i));
m_CriticalSection.Unlock();
}
Consider using CSingleLock so that the constructor takes care of the locking and the destructor automatically takes care of the unlocking
void CThreadingEx4Dlg::MyFunction(int minCount,int maxCount)
{
CSingleLock myLock(&m_CriticalSection, TRUE);
// do work here.
// The critical section will be unlocked when myLock goes out of scope
}

Resources