我曾尝试在64位Ubuntu中使用 setjmp / longjmp ,但它不能正常工作,而它在32位Ubuntu中正常工作。任何想法,发生了什么。以下是代码,我试图执行。
在64位上,它会在longjmp之后返回时挂起。在维基百科关于setcontext的文章中,它表示它与64位无法正常工作。我们在 setjmp 时遇到同样的问题吗?事实上,我试图使用 setjmp ,以避免 setcontext 的问题,但它似乎在64位上有相同的问题。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <string>
#include <setjmp.h>
#define NOFTHREADS 2
#define DATASIZE 500
#define SETSIZE (DATASIZE / NOFTHREADS)
int data[DATASIZE];
pthread_mutex_t sumMutex;
pthread_mutex_t prodMutex;
int sum;
double prod;
static jmp_buf buf;
int jmp_onced[NOFTHREADS+1];
#define lock pthread_mutex_lock
#define unlock pthread_mutex_unlock
void *SumThread( void *pParam )
{
unsigned int tid = *((unsigned int*)(pParam));
int si = tid * SETSIZE;
int i, j, oi, local_sum;
double local_prod;
pthread_attr_t attr;
if ( setjmp(buf) )
printf( "%d: tid %u back! <<<<<<<<<\n", getpid(), tid );
if ( jmp_onced[tid] )
goto end_this;
printf( "%d: >>>>>>>>>>>>> tid %u, starting <<<<<<<<<<<<\n\n", getpid(), tid );
for( oi = 0; oi < 5; oi++ )
{
local_sum = 0;
local_prod = 1.0;
for( i = si; i < (si+SETSIZE); i++ )
{
local_sum = local_sum + data[i];
if ( data[i ] )
local_prod *= 0.005 * data[i];
}
lock( &sumMutex );
sum += local_sum;
unlock( &sumMutex );
lock( &prodMutex );
prod *= local_prod;
unlock( &prodMutex );
}
printf( "%d: !!!!!!!!!!!!!!tid %u done!!!!!!!!!!!!!!\n\n", getpid(), tid );
jmp_onced[tid] = 1;
longjmp( buf, 1 );
end_this:
printf( "%d: ****** tid %u is exiting! ******\n", getpid(), tid );
return 0;
}
void real_main()
{
pthread_t hThread[NOFTHREADS];
int index[NOFTHREADS];
int i, pid, err;
time_t t1 = time(NULL);
printf( "%d: Inside real_main, primary thread = %lx!\n", getpid(), pthread_self() );
for( i = 0; i < NOFTHREADS; i++ )
{
index[i] = i;
pthread_create( &hThread[i], NULL, SumThread, &index[i] );
}
for( i = 0; i < NOFTHREADS; i++ )
pthread_join( hThread[i], NULL );
printf( "Sum of numbers from 1 to %d is %d\n", DATASIZE, sum );
printf( "Prod of numbers from 1 to %d is %g\n", DATASIZE, prod );
printf( "\n\n[[[[[ %d(child of %d): Time taken = %lu seconds ]]]]]\n\n", getpid(), getppid(), time(NULL) - t1 );
}
int main(int argc, char **argv)
{
int pid, i, err;
printf( "size of long is %d\n", sizeof( long ) );
sumMutex = PTHREAD_MUTEX_INITIALIZER;
prodMutex = PTHREAD_MUTEX_INITIALIZER;
printf( "pid = %d, @sumMutex = %lx, @prodMutex = %lx\n", getpid(), (long)&sumMutex, (long)&prodMutex );
for( i = 0; i < DATASIZE; i++ )
data[i] = i+1;
switch(pid = fork())
{
case -1:
printf("fork failed");
break;
case 0: // Child
printf( "Child pid() = %d\n", getpid() );
real_main();
break;
default:// Leader
printf( "Parent pid() = %d\n", getpid() );
real_main();
}
printf( "getppid() = %d, getpid() = %d\n", getppid(), getpid() );
return 0;
}
答案 0 :(得分:5)
您需要为每个帖子使用单独的jmp_buf
。目前你正在重复使用同一个。
答案 1 :(得分:1)
如果您没有声明本地变量volatile
,并且在调用setjmp()
后更改了这些变量,则在致电longjmp()
时无法保证保留这些变量。
(C99标准中的7.13.2.1/3。)
但这似乎不适用于此,因为si
和tid
不会更改。