我從高級Linux編程書中獲得了此代碼。當我嘗試在Linux 64位環境下執行代碼時,函數調用後which_prime
變量的值被破壞(更改爲0)。pthread_join損壞堆棧中的pthread_create參數
在這個例子中爲什麼which_prime
值運行在pthread_join後,被破壞?
一般我們可以使用傳遞給pthread_create的安全函數內部主即使我們所說的其他功能,如pthread_join()
的第四個參數?
#include <pthread.h>
#include <stdio.h>
/* Compute successive prime numbers (very inefficiently). Return the
Nth prime number, where N is the value pointed to by *ARG. */
void* compute_prime (void* arg)
{
int candidate = 2;
int n = *((int*) arg);
while (1) {
int factor;
int is_prime = 1;
/* Test primality by successive division. */
for (factor = 2; factor < candidate; ++factor)
if (candidate % factor == 0) {
is_prime = 0;
break;
}
/* Is this the prime number we’re looking for? */
if (is_prime) {
if (--n == 0)
/* Return the desired prime number as the thread return value. */
return (void*) candidate;
}
++candidate;
}
return NULL;
}
int main()
{
pthread_t thread;
int which_prime = 5000;
int prime;
/* Start the computing thread, up to the 5,000th prime number. */
pthread_create (&thread, NULL, &compute_prime, &which_prime);
/* Do some other work here... */
/* Wait for the prime number thread to complete, and get the result. */
pthread_join (thread, (void*) &prime);
/* Print the largest prime it computed. */
printf(「The %dth prime number is %d.\n」, which_prime, prime);
return 0;
}
這裏有一個提示:原型爲'pthread_join'是'INT在pthread_join(的pthread_t線程,無效** RETVAL);' - 在那第二個參數密切關注。 – 2015-02-18 03:56:16