If pthread_cond_wait() requires locked mutex, doesn't it block the thread which changed condition?

Advertisements I need a two-threaded application. One thread prepare data, one process it. If there is no data to process, the second thread should sleep. Doing as tons of tutorials suggests: pthread_mutex_t mtx; pthread_cond_t cond; char *shared_data = NULL; char *process_data() { char *dt; pthread_mutex_lock(&mtx); if(!shared_data) pthread_cond_wait(&cond, &mtx); dt = strdup(shared_data); free(shared_data); shared_data = NULL;… Read More If pthread_cond_wait() requires locked mutex, doesn't it block the thread which changed condition?

Thread creation in C

Advertisements Can somebody please explain why the following loop for thread creation fails without the sleep function call? for(t=0; t<NUM_THREADS; t++) { printf("Main: creating thread %d\n", t); rc = pthread_create(&thread[t], NULL, BusyWork, (void *)&t); sleep(1); if (rc) { perror("pthread_create"); exit(EXIT_FAILURE); } } If sleep is not inserted then thread function seems to take as an… Read More Thread creation in C

Casting a struct to a void pointer and back again in a different thread changes member values

Advertisements I am running some code using pthreads, and to pass information to the thread’s function, I am using a struct. The struct (called struct tinfo) has two fields, one is a pointer to another struct and the other is an int, called socket. I am debugging using GDB, and prior to starting the new… Read More Casting a struct to a void pointer and back again in a different thread changes member values

How can I make std::thread not struck the pragma?

Advertisements I want to design a timer class, there is a function, which sleep some seconds, then call other function. please see the code: #include <thread> #include <iostream> void func() { printf("timer thread function called\n"); } class Timer { public: template <typename Fn> void sleep_start(int sec, const Fn& f) { printf("sleep %d\n", sec); td_ =… Read More How can I make std::thread not struck the pragma?

Simple pthread prog: segmentation fault

Advertisements Trying to see how pthread works by running a simple program but I am getting segmentation fault (core dumped) at pthread_create #include <stdio.h> #include <pthread.h> #include <stdlib.h> void* testfunc(void* arg) { while (1) { printf("testfunc"); } } int main(void) { printf("helo\n"); if (pthread_create(NULL, NULL, &testfunc, NULL) != 0) { perror("pthread failed to create\n"); }… Read More Simple pthread prog: segmentation fault