2

I have create small program which is working with pthreadVC.lib which is Win32 version. I am using visual studio 2013.

When I have changed program setting for x64 od same program and then I have linked pthreadVC2.lib (which for x64 configuration) and then my program crashing at pthread_join also instead of join I used pthread_cancel but having same issue . Also I have build pthread myself for x64 and linked that library but still having same problem.

My Test Code

#include<stdio.h>
#include<pthread.h>

pthread_mutex_t mutex = NULL; 
pthread_cond_t cond = NULL;

void test(){
    pthread_mutex_lock(&mutex);

    printf("\n Threads Working");

    pthread_mutex_unlock(&mutex);
}

void main() {

    pthread_t threadid;

    pthread_create(&threadid,NULL,(void*)test,NULL);

    pthread_join(threadid,NULL);

    printf("\n FINISH ");
    if (getchar())
        return;
} 

Error which get on x64 configuration is

Unhandled exception at 0x0000000180002C70 (pthread_dll.dll) in Pthread64_bit.exe: 0xC0000005: Access violation reading location 0x000000000000001A.

Edit : Also I have copied example from pthreads in C – a minimal working example and try to run but having same error in pthread_join .

So can you tell me is there any other setting need to do for x64 or where I missing?

2501
  • 25,460
  • 4
  • 47
  • 87
Mohan
  • 1,871
  • 21
  • 34

1 Answers1

2

The mutexes must be initialized, before they are being used. You initialize them to NULL, and then try to use them. This is wrong.

The error message is a clear indicator that a NULL pointer is being dereferenced at a small offset, a member of a struct is being accessed: Access violation reading location 0x000000000000001A.

Therefore remove the incorrect initialization, and initialize the mutex before use:

const int error = pthread_mutex_init( &mutex );
if( error ) 
{
    //handle error
}

and delete it when it is no longer being used:

const int error = pthread_mutex_destroy( &mutex );
if( error ) 
{
    //handle error
}

Alternatively mutexes can be initialized with: PTHREAD_MUTEX_INITIALIZER:

pthread_mutex mutex = PTHREAD_MUTEX_INITIALIZER ;

They should still be deleted using pthread_mutex_destroy().

The other problem is the function passed to pthread_create(). It's type must be void*(*)(void*). The type of your function is void(*)(). Even though you used a cast, this isn't correct and causes undefined behavior.

2501
  • 25,460
  • 4
  • 47
  • 87
  • yes you are correct up voted, but still I have same problem in pthread_join – Mohan Mar 05 '16 at 10:13
  • i have changed my function prototype to `void* test(void*pt)` and pthread call to `pthread_create(&threadid, NULL, &test, NULL);` still have problem – Mohan Mar 05 '16 at 12:19
  • 1
    Actually it's solved my half problem and half by downloading recent API from https://sourceforge.net/projects/pthreads4w/files so i have accepted it and suggested edit to you. – Mohan Mar 08 '16 at 11:18