PThreads Error: argument of type "void *(*)()" is incompatible - pthreads

I'm not too sure how to debug this, I am completely new to threads and am following a tutorial which worked 100%, but not for me:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void* sample() {
printf("Thread sample. \n");
}
int main(void) {
// Thread Creation
pthread_t tid; // Creation of thread pointer.
pthread_create(&tid, NULL, &sample, NULL); // Creation of thread.
// Waiting for threads to be completed:
pthread_join(tid, NULL);
return 0;
}
I get the error: argument of type "void ()()" is incompatible with parameter of type "void ()(void *).
All I am doing is following exactly the tutorial from: https://www.youtube.com/watch?v=aVyeJQuSFEU
Except I did not open the file and delete those things on line 317 (since it wasn't there). But VS recognizes the pthread library now.
Any help is sincerely appreciated.

I get the error: argument of type "void ()()" is incompatible with parameter of type "void ()(void *).
The error is telling you exactly the problem: you defined your void* sample() function to take no arguments, but you should define it the way pthread_create expects: void* sample(void *ptr) {...}.
If you don't need the input ptr parameter, you can simply not use it.
P.S. There is an additional bug in your sample() function: it promised to return void*, but doesn't. To fix this, add return NULL;.
P.P.S. The tutorial may be correct in the way it adds pthread.h etc to Visual Studio, but is wrong in its use of pthread_create(). You'll be better off finding something more authoritative.

Related

How to explain this glibc modification on libpthread?

We found an issue while we upgrade Yocto from 1.7 to 2.2.
App below behaves differently on newer glibc, it always got stuck on pthread_cond_destroy on glibc2.25, while on glibc2.20 it ends well.
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *thread1(void *);
void *thread2(void *);
int main(void)
{
pthread_t t_a;
pthread_t t_b;
pthread_create(&t_a,NULL,thread1,(void *)NULL);
pthread_create(&t_b,NULL,thread2,(void *)NULL);
sleep(1);
pthread_cond_destroy(&cond);
pthread_mutex_destroy(&mutex);
exit(0);
}
void *thread1(void *args)
{
pthread_cond_wait(&cond,&mutex);
}
void *thread2(void *args)
{
}
After investigation I find a glibc commit here:
https://sourceware.org/git/?p=glibc.git;a=commit;f=sysdeps/arm/nptl/bits/pthreadtypes.h;h=ed19993b5b0d05d62cc883571519a67dae481a14, which seems to be the reason.
We noticed the comment of __pthread_cond_destroy, it mentioned:
A correct program must make sure that no waiters are blocked on the
condvar when it is destroyed.
It must also ensure that no signal or broadcast are still pending to
unblock waiters.
and destruction that is concurrent with still-active waiters is
probably neither common nor performance critical.
From my perspective it brings in a defect. But glibc team seems to have a good reason. Could anybody explain whether this modification is necessary?
From the standard:
Attempting to destroy a condition variable upon which other threads
are currently blocked results in undefined behavior.
From my perspective it brings in a defect.
Your program depended on undefined behavior. Now you pay the price of doing so.

Can I use pthread_join() to check for terminated thread?

I need to know if some thread already terminated (if it's not, I must wait for it).
If I call pthread_join() on terminated thread, it always returns success in my version of glibc.
But documentation for pthread_join() says that it must return error with code ESRCH if thread already terminated.
If I call pthread_kill(thread_id, 0) it returns with error code ESRCH (as expected).
Inside glibc sources I see that inside pthread_join() there is simple checking for valid thread_id, but not real checking if thread exist.
And inside pthread_kill() there is real checking (in some kernel's list).
There is my test program:
#include <errno.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
void * thread_func(void *arg)
{
printf("Hello! I`m thread_func!\nGood-bye!\n");
return NULL;
}
int main(void)
{
int res;
pthread_t thread_id;
printf("Hello from main()!\n");
pthread_create(&thread_id, NULL, thread_func, NULL);
printf("Waiting...\n");
sleep(3);
res = pthread_join(thread_id, NULL);
printf("pthread_join() returned %d (%s)\n", res, strerror(res));
res = pthread_kill(thread_id, 0);
printf("pthread_kill() returned %d (%s)\n", res, strerror(res));
return 0;
}
It's output:
Hello!
Waiting...
Hello! I`m thread_func!
Good-bye!
pthread_join() returned 0 (Success)
pthread_kill() returned 3 (No such process)
My question: is it safe to use pthread_join() to check for terminated threads or I must always use pthread_kill()?
When a thread exits, the code for it stops running but its "corpse" is left lying around, for the return code to be collected by the parent.(1)
So, even though you think the thread has totally disappeared, that's not actually the case.
A call to pthread_join will examine said corpse for a return code so that the parent is notified as to how things turned out. After that's been collected, the thread can be truly laid to rest.(2)
That's why pthread_join() is returning a success code and pthread_kill is not - you're not allowed to kill a thread that's already dead, but you are allowed to join to one that's dead but still warm :-)
You may be better educated by trying the following code, which tries to join to the thread twice:
#include <errno.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
void * thread_func(void *arg) {
printf("Hello! I`m thread_func!\nGood-bye!\n");
return NULL;
}
int main(void) {
int res;
pthread_t thread_id;
printf("Hello from main()!\n");
pthread_create(&thread_id, NULL, thread_func, NULL);
printf("Waiting...\n");
sleep(3);
res = pthread_join(thread_id, NULL);
printf("pthread_join() returned %d (%s)\n", res, strerror(errno));
res = pthread_join(thread_id, NULL);
printf("pthread_join() returned %d (%s)\n", res, strerror(errno));
return 0;
}
On my system, I see:
Hello from main()!
Waiting...
Hello! I`m thread_func!
Good-bye!
pthread_join() returned 0 (No error)
pthread_join() returned 3 (No error)
In other words, though the thread is dead, the first pthread_join() works.
(1) You can pthread_detach a thread so that its resources are immediately released on termination, if you so wish. That would be along the lines of:
pthread_create(&thread_id, NULL, thread_func, NULL);
pthread_detach(thread_id);
but I'm pretty certain then a join will fail in that case even if the thread is still alive.
To see if a thread is still running regardless of whether it's detached or not, you can just use:
if (pthread_kill(thread_id, 0) != 0)
// Thread is gone.
(2) Apologies for the morbid tones of this answer, I'm feeling a little dark today :-)
pthread_join end the thread's uses of resources. It returns 0 when the thread has come to an end point and is ready to be cleaned up. Threads do not 'go away' all by themselves by default.
Returning zero means:
1. the thread got cleaned up
2. the thread WAS still there waiting
So no, do not use pthread_kill, you have a major assumption that is wrong: threads, unless set to be non-joinable do not exit and cleanup stack and memory resources when the thread returns. In other words, return NULL in you example di NOT terminate the thread. pthread_join did.
So, yes, use pthread_join to wait for a thread to complete.

iOS using pthread_mutexattr_t trouble

i am porting an existing c++ project to objective-c++ and came across this mutex stuff. I am not sure what is done here neither if it is correct. To initialize some kind of multithreading lock mechanism (called "CriticalSection") the following is done:
#include <pthread.h>
pthread_mutex_t cs;
pthread_mutexattr_t attr;
Later in code:
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&cs, &attr);
To enter the "lock" there is:
pthread_mutex_lock(&cs);
To leave the "lock":
pthread_mutex_unlock(&cs);
pthread_mutex_destroy(&cs);
My question (since I have no clue how this is done) is: Does this look like a correct implementation?
Because I encounter problems that look like the lock mechanism just does not work (bad memory access errors, corrupt pointers in situations where the "CriticalSection" was used).
It's correct except that you don't want to destroy the mutex when unlocking. Only destroy the mutex when you can guarantee that all threads have finished with the it.
for example:
class CriticalSection
{
public:
CriticalSection()
{
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mutex, &attr);
}
~CriticalSection() { pthread_mutex_destroy(&mutex); }
void Enter() { pthread_mutex_lock(&mutex); }
void Leave() { pthread_mutex_unlock(&mutex); }
private:
pthread_mutex_t mutex;
};

Why the child thread block in my code?

I was trying to test the pthread by using mutex:
#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int global = 0;
void thread_set();
void thread_read();
int main(void){
pthread_t thread1, thread2;
int re_value1, re_value2;
int i;
for(i = 0; i < 5; i++){
re_value1 = pthread_create(&thread1,NULL, (void*)&thread_set,NULL);
re_value2 = pthread_create(&thread2,NULL,(void*)&thread_read,NULL);
}
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
/* sleep(2); */ // without it the 5 iteration couldn't finish
printf("exsiting\n");
exit(0);
}
void thread_set(){
pthread_mutex_lock(&mutex1);
printf("Setting data\t");
global = rand();
pthread_mutex_unlock(&mutex1);
}
void thread_read(){
int data;
pthread_mutex_lock(&mutex1);
data = global;
printf("the value is: %d\n",data);
pthread_mutex_unlock(&mutex1);
}
without the sleep(), the code won't finish the 5 iteration:
Setting data the value is: 1804289383
the value is: 1804289383
Setting data the value is: 846930886
exsiting
Setting data the value is: 1804289383
Setting data the value is: 846930886
the value is: 846930886
exsiting
It works only add the sleep() to the main thread, I think it should work without the sleep(), because the join() function wait for each child thread terminate
Any one can tell me why is it?
Your use of mutex objects looks fine, but this loop
for(i = 0; i < 5; i++) {
re_value1 = pthread_create(&thread1,NULL, (void*)&thread_set,NULL);
re_value2 = pthread_create(&thread2,NULL,(void*)&thread_read,NULL);
}
is asking for trouble as you are reusing the same thread instances thread1 and thread2 for each iteration of your loop. Internally this must be causing problems although I do not know exactly how it would manifest itself. You should really use a separate instance of thread object per thread you want to ensure reliable running. I do not know what would happen if you called pthread_create using an instance of a thread object that is already running but I suspect it is not a wise thing to do. I would suspect that at best it will block until the thread function has exited.
Also you are not cheking the return values from pthread_create() either which might be a good idea. In summary I would use a separate instance of thread objects, or add the pthread_join calls to the inside of your loop so that you are certain that the threads are finished running before the next call to pthread_create().
Finally the function signature for functions passed to pthread_create() are of the type
void* thread_function(void*);
and not
void thead_function()
like you have in your code.
You are creating 10 threads (5 iterations of two threads each), but only joining the last two you create (as mathematician1975 notes, you're re-using the thread handle variables, so the values from the last iteration are the only ones you have available to join on). Without the sleep(), it's quite possible that the scheduler has not started executing the first 8 threads before you hit exit(), which automatically terminates all threads, whether they have had a chance to run yet or not.

opencv characters void segmentation

i use this functions to segment characters image ,but the programme crach ,somone can help me please to found solution why it crach?
You need to pinpoint the line that causes the crash. For that I can think in 2 ways:
Use a debugger;
or if you are afraid of that, use the printf() method:
The printf() method involves placing a printf() call after each function call in your program, so when you run your application you can see in the console what was the last printf() message. That will help you locate the code that is responsible for the crash. Example:
printf("dbg10\n");
IplImage *img_cv = cvLoadImage("plaque.jpg");
printf("dbg20\n");
cvSetImageROI(img_cv,cvRect(8,10,60,35));
printf("dbg30\n");
IplImage *img_pl = cvCreateImage( cvGetSize(img_cv),img_cv->depth,img_cv->nChannels);
printf("dbg40\n");
cvCopy(img_cv,img_pl, NULL);
printf("dbg50\n");
cvResetImageROI(img_cv);
printf("dbg60\n");
//etc
From what I saw in your code, the first 2 calls have the potential to crash your application: if cvLoadImage() fails to load an image it will return a NULL pointer. Since the next function receives the pointer as a parameter, it will try to dereference the null pointer and that can a crash. Solution? Always check the freaking return of the calls you make:
IplImage *img_cv = cvLoadImage("plaque.jpg");
if (!img_cv)
{
printf("Failed to load image.\n");
exit(1);
}
cvSetImageROI(img_cv,cvRect(8,10,60,35));

Resources