|
小弟在调试程序时发现一个问题:
如果编译时用了-O参数的话.在一些调用pthread_cancel的情况下会出现"Segmentation fault".
不加-O参数则没有遇到过.
下面是简化后的代码,大虾帮忙看一下是不是的代码的问题.
#include <pthread.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sched.h>
#include <fcntl.h>
#include <unistd.h>
#include <semaphore.h>
#include <stdio.h>
#include <errno.h>
int usec_sleep(unsigned long usec) {
struct timeval time_out;
time_out.tv_sec = usec / 1000000;
time_out.tv_usec = usec % 1000000;
while (select(0, NULL, NULL, NULL, &time_out) == -1) {
if (errno != EINTR)
return -1;
}
return 0;
}
static sem_t target_lock;
static void* do_something(void *data) {
int i;
while (1) {
sem_wait(&target_lock);
// do something
sem_post(&target_lock);
for (i = 0; i < 64; ++i)
//do something
usec_sleep(8000);
}
pthread_exit(NULL);
}
int main(int argc, char *argv[]) {
int in, fd, lock_free;
pthread_t thread;
lock_free = 0;
sem_init (&target_lock, 0, 0);
pthread_create(&thread, NULL, do_something, NULL);
while (1) {
scanf("%d", &in);
if (in == -1) {
break;
}
if (in == 0) {
if (lock_free)
sem_wait(&target_lock);
lock_free = 0;
}
if (in == 1) {
if (lock_free) {
sem_wait(&target_lock);
// do something
sem_post(&target_lock);
}
else {
// do something
sem_post(&target_lock);
}
lock_free = 1;
}
}
pthread_cancel(thread);
pthread_join(thread, NULL);
}
当用 gcc -O test.c -lpthread编译后:
[daemeon@localhost tmp]$ ./a.out
1
0
-1
Segmentation fault |
|