just to clarify the above code does nothing real the target was to create a crash
by creating "sem" in a way you should not
what i could not manage
thats why i override the new operator and used malloc and created 2 different
sem vs sem_p
my current conclusion is that this lines from the documentation is meaningless
unless you take extra care in some fancy way that "sem" is not reachable from other threads
maybe thread_local or some thing similar
the main reason for this is i will have a bunch of threads doing some work in some situation they need to outsource parts of their job as it would take to long during which time the thread could not react to new incoming signals
so i will have a threadpool from which they request an extra thread
set up what to do and start the thread (sem_post)
as long i understand its relatively expensive to start a thread so i think its better to reuse them
so "sem" could be created and unlocked from a bunch of different threads thats why i want to understand what they mean by "or a variable
allocated dynamically on the heap"
this is some actual code : (there is an other class managing a list of workers)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
namespace XY{
class WORKER{
public:
WORKER();
WORKER(const WORKER& orig);
virtual ~WORKER();
sem_t *thread_sem;
void (*job)(void*);
void *job_obj;
private:
pthread_t thread_id;
static void* thread(void *in);
};
}
XY::WORKER::WORKER(){
thread_sem = (sem_t*) malloc(sizeof(sem_t)); // as i am not sure
//what the documentation says
sem_init(thread_sem, 0, 0);
pthread_create(&thread_id, NULL, thread, this);
}
XY::WORKER::~WORKER() {
}
void* XY::WORKER::thread(void *in){
WORKER *worker = (WORKER*)in;
do{
WORKER *worker = (WORKER*)in;
sem_wait(worker->thread_sem);
worker->job(worker->job_obj);
//put it back to the thread pool .....
}while(1);
}
|