/*函数atomic_signal_fence范例*/
#ifdef __STDC_NO_ATOMICS__
#error "Implementation does not support atomic types."
#endif
#ifdef __STDC_NO_THREADS__
#error "Implementation does not support multi-threads."
#endif
#include <signal.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <threads.h>
atomic_int aNumber = 0;
int number;
/*信号处理函数。*/
void sigfpeHandler(int sig)
{
/*其它代码。*/
while(!atomic_load_explicit(&aNumber, memory_order_relaxed))
;
atomic_signal_fence(memory_order_acquire);
puts("Floating-point exception.");
/*其它代码。*/
}
/*新线程中执行的函数。*/
int func(void *arg)
{
/*设置信号处理函数。*/
if(signal(SIGFPE, sigfpeHandler) == SIG_ERR)
{
perror("Failed to install SIGFPE handler.");
exit(EXIT_FAILURE);
}
printf("Input the value of number: ");
scanf("%d", &number);
atomic_signal_fence(memory_order_release);
atomic_store_explicit(&aNumber, 1, memory_order_relaxed);
if(number)
{
/*执行其它运算,例如:10/number。*/
}
else
{
raise(SIGFPE);
}
thrd_exit(0);
}
int main(void)
{
thrd_t threadId;
if(thrd_create(&threadId, func, NULL) != thrd_success)
{
fputs("Fail to create thread.", stderr);
exit(EXIT_FAILURE);
}
thrd_join(threadId, NULL);
return 0;
}
|