LoveUnix » 编程开发 & Rational » pthread_cancel的问题
让LU留住您的每

一天 让LU博客留住您的每一天
2006-2-8 12:47 YZ
pthread_cancel的问题

很简单的情况,创建两个线程,第2个去cancel第1个。
但如果 f1 中的 localtime_r 和 sem 同时打开执行, f2 在 join时阻塞;
如果只开任何一个, f2 的join 成功。
困惑中,请高手指点! (redhat 8.0)

#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <time.h>

#define LEN 128
#define PATH "./"

pthread_t tid[2];

char filename[LEN];
FILE *f;

void *f1(void *p)
{
    pthread_setcancelstate( PTHREAD_CANCEL_ENABLE, NULL);
    pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);

    printf( "in %s\n", __FUNCTION__ );
    time_t ta;
    struct tm tb;

    ta = time( NULL );
#if 1
    localtime_r( &ta, &tb );
#else
    memset( &tb, 0, sizeof(tb) );
#endif


#if 1
    sem_t sem;
    sem_init( &sem, 0, 0);
    sem_wait( &sem );
#else
    sleep(1000);
#endif
}

void *f2(void *p)
{
    pthread_setcancelstate( PTHREAD_CANCEL_ENABLE, NULL);
    pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);

    printf( "in %s\n", __FUNCTION__ );

    pthread_cancel( tid[0] );
    printf( "f2: join ...\n");
    pthread_join( tid[0], NULL);

    printf( "f2: join ok !\n" );
}


int main()
{

  pthread_attr_t tattr;
  pthread_attr_init( &tattr);
  pthread_attr_setdetachstate( &tattr, PTHREAD_CREATE_JOINABLE);

  pthread_create( &tid[0], &tattr, f1, NULL);
  sleep(5);
  pthread_create( &tid[1], &tattr, f2, NULL);

  printf( "press ...\n" );
  getchar();
}

2006-3-24 08:56 eldwin
我在RHAS3及RH9.0上,也用gcc 296及322版本编译过都没问题。

页: [1]
查看完整版本: pthread_cancel的问题


Powered by Discuz! Archiver 5.5.0  © 2001-2006 Comsenz Inc.