How to pass a pointer parameter to a thread

Hi. I’m just wondering whether it is possible to pass a pointer address to another thread and modify its value or vex::thread can’t take it.

Welcome to the VEX Forum!

If I’m understanding what you are asking correctly, I suspect vex::thread has a deliberate limitation preventing such behavior. This is due to something called a race condition, which is caused by multiple threads trying to access the same memory address at the same time. Depending on what each thread is doing, this often results in undefined behavior, which can be particularly hard to debug. If I were you, I would seriously consider whether the code you intend to run in a new thread can be integrated into other parts of the code, or, if it absolutely needs to be in a new thread, run it with a copy of the variable made at that start of the thread.

If worse comes to worst, and you have to be able to change the variable from this new thread, you have to be able to guarantee that no other threads will try to modify its value either, as well as accepting that any threads reading from the variable may be using out-of-date data. Although I’ve not really touched it much, I’ve heard that std::atomic is really useful in this case, and I would suggest googling it for a bit of information.

Hope this helps!

1 Like

Thx for reply.

int interrupte(int* a) {
  *a = 1;
}

void usercontrol() {
  int a = 0;
  thread t1(interrupte, &a)
  while (1) {
    //something;
    if (a == 1) {
      break;
    }
  }
  while (1) {
    //something;
    if (a == 1) {
      break;
    }
  }
}

This is what I want to do and variable is only used in one thread so I think race condition problem is fine.

Although the code looks fine, I think there is probably a better way to do what you are trying to achieve. What if you swapped the thread for a task, and put your //something code into that task instead?

This would mean that instead of having a shared variable, you could just call {task name}.stop()

An example:

int callback() {
  // Some code
  return 0;
}

void usercontrol() {

  task t1(callback);
  // Code before interupt goes here

  t1.stop();
  
}

Sorry if this code isn’t quite right in VexCode, I’ve never actually used it (only PROS), so I’m not really familiar with its API :crossed_fingers:

sorry I forgot to say that I wanted to make interrupt function. Within while there should be code that takes about 3 seconds which holds up whole usercontrol, and I made a thread that keeps watching whether I pressed lets say L2 button. When I do it, it makes a = 1 and while breaks. But I can only do it by making a as global variable.