0

有没有办法强制线程拥有独立的地址空间?我想让许多线程使用局部变量运行循环 - 但似乎它们都共享相同的变量。

例如

for (i = args->start; i < args->end; i++) {
        printf("%d\n", i);
        if (quickFind(getReverse(array[i]), 0, size - 1)) {
            printf("%s\n", array[i]);
            //strcpy(array[i], "");
        }
    }

i似乎是跨线程共享的。

4

4 回答 4

0

Short answer: Yes it's possible for each thread to have its own copy of the variable i.

Long answer:

All threads share the same address space and the OS does not provide any protection to prevent one thread from accessing memory used by another. However, the memory can be partitioned so that it will only be accessed by a single thread rather than being shared by all threads.

By default each thread receives its own stack. So if you allocate a variable on the stack then it will typically only be accessed by a single thread. Note that it is possible to pass a pointer to a stack variable from one thread to another, but this is not recommended and could be the source of the sort of problems that you are seeing.

Another way for a thread to receive its own copy of a variable is using thread local storage. This allows each thread to have its own copy of a global variable.

In summary, although threads share an address space they can work on private data. But you need to be careful with how you are sharing data between threads and avoid data races.

于 2013-10-04T21:43:30.533 回答
0

如果你真的很懒惰,并且不做任何设计更改(不是真的推荐),你可以将声明修改为类似的i东西__thread int i,这样每个线程都会有它自己的变量实例。

如果您使用的是 OpenMP 而不是 Posix 线程,您也可以#pragma omp threadprivate(i)在第一次使用i.

于 2013-10-05T00:07:04.490 回答
0

只需让每个线程分别调用函数即可。函数的每次调用都会获得所有局部变量的自己的实例。如果这不是真的,递归将不起作用。

于 2013-10-04T23:56:20.727 回答
0

线程共享其父进程的内存空间。是他们的特色。如果您不希望这种情况发生,您可以使用 fork() 创建一个新进程,该进程将拥有自己的地址空间。

如果您决定使用 fork() 请记住,在成功创建子进程时,它会将 0 返回给子进程,并将子进程的 PID 返回给父进程。

于 2013-10-04T03:27:05.317 回答