小编Jun*_*une的帖子

如何从main()发送取消请求到线程?

我需要在thread_B中阻塞Ctrl+Csignal(SIGINT)并且main()应该处理SIGINT信号,所以每当用户按下Ctrl+Cmain()时应该尝试取消thread_B但是thread_B需要忽略前100秒的任何取消请求,任何取消请求应该在100之后兑现.秒和thread_B终止后main()应该终止,到目前为止我能够阻止thread_B中的信号但是不能从main()向thread_B发送取消请求,我该如何解决?

编辑:当线程运行在while循环SIGINT被禁用时,它不会接受任何Ctrl+C请求,因此它将永远循环,如何main()中断while循环以便它可以向线程发送取消请求?对此有何看法?

码:

#include <pthread.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <math.h>

#define handle_error_en(en, msg) \
       do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)

static volatile sig_atomic_t doneflag = 0;

/* ARGSUSED */
static void setdoneflag(int signo) {
    doneflag = 1;
}

static void *
thread_func(void *ignored_argument)
{
   int s;

    sigset_t sigset;
    sigemptyset(&sigset);
    sigaddset(&sigset, SIGINT);
    sigprocmask(SIG_BLOCK, &sigset, NULL);

    while …
Run Code Online (Sandbox Code Playgroud)

c multithreading posix signals

6
推荐指数
1
解决办法
284
查看次数

使用 POSIX 信号量的可重用屏障实现

需要一个创建 5 个 pthread 的解决方案。每个 pthread 执行一个函数,该函数涉及循环 10 次。在循环的每次迭代中,线程将 int 从 0 增加到 0.9*MAX_INT,然后打印迭代编号。确保 5 个线程中的每一个都在它们可以开始第 (i+1) 次迭代之前完成循环的第 i 次迭代(即所有线程在每次迭代结束时同步/会合)。我需要使用使用 POSIX 信号量实现的两阶段屏障来强制执行同步约束

我写了以下代码我正确吗?

#include <stdio.h>

#include <stdlib.h>

#include <pthread.h>

int thread_count;

void* MyThread(void* rank);

int main()

{

  long thread;

   pthread_t* thread_handles;

   thread_count = 5;

   thread_handles = malloc (thread_count*sizeof(pthread_t));

   for (thread = 0; thread < thread_count; thread++)

       pthread_create(&thread_handles[thread],NULL,MyThread,(void*) thread);

   for (thread = 0; thread < thread_count; thread++)

       pthread_join(thread_handles[thread], NULL);

   free(thread_handles);

   return 0;

}

void* Hello(void* rank)

{

    long my_rank = (long) …
Run Code Online (Sandbox Code Playgroud)

c multithreading synchronization semaphore pthreads

0
推荐指数
1
解决办法
4393
查看次数