0

For some code I am writing I am trying to get a threads but I keep getting an error. I am programming on linux in visual studio code.

This is the code:

void* start(void *s) {
    int me = (int*)s;
    //int me = pthread_self();
    printf("Entered: %d\n", me);

    Lock(me);

    printf("TEST 1");
    for (int i = 0; i<MAX; i++) ans++;
    printf("TEST 2");

    Unlock(me);
    printf("TEST 3");

    return NULL;
}


pthread_create(&thread1, NULL, start, (void*)0);
pthread_create(&thread2, NULL, start, (void*)1);

The pthread creates are inside of a main method. The error I'm getting:

error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive] 49 | int me = (int*)s; | ^~~~~~~ | | | int*

Fuey500
  • 72
  • 1
  • 9

1 Answers1

0

int* is a pointer to a value, not the value itself. You have passed a value cast as a pointer and you should cast it back to a value:

int me = reinterpret_cast<int>(s);
StenSoft
  • 9,369
  • 25
  • 30
  • From examples that I have seen for this (it's the petersons algo) they do it this way. I'm still learning and not well versed with programming c++ on linux. Also when I try your code I get a similar casting error: error: cast from ‘void*’ to ‘int’ loses precision [-fpermissive] 49 | int me = reinterpret_cast(s); | – Fuey500 Oct 07 '20 at 03:08
  • The examples then have to pass different arguments in `pthread_create` than you. If it fails with precision loss (on a 64-bit computer), you can `reinterpret_cast` it to `ptrdiff_t`. – StenSoft Oct 07 '20 at 03:12
  • I have resolved my issue: *((int*)(&s)); is what I needed to use. I used this thread: https://stackoverflow.com/questions/1640423/error-cast-from-void-to-int-loses-precision to figure out what was wrong. I did try some other attempts but I'll have to get a better understanding of what went wrong, currently I'm a little confused. – Fuey500 Oct 07 '20 at 03:19