我正在尝试为我的多线程应用程序编写安全的 SIGINT 处理,并且我正在使用 sleep()
函数来模拟进入“不安全”区域 - 一个不应取消线程的地方.这是我的代码:
全局变量:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
pthread_mutex_t *global_mutex;
pthread_mutex_t **thread_mutexes;
pthread_mutex_t *firm_mutex;
pthread_attr_t *attr;
主题:
void *thread(void *data)
{
int local_tid = *(int *) data;
printf("Starting thread %d\n", local_tid);
for (;;) {
pthread_mutex_lock(thread_mutexes[local_tid]);
int scnds = rand() % 5 + 1;
printf("%d locked\nSleeping for: %d seconds\n", local_tid, scnds);
sleep(scnds);
printf("%d woken up!\n", local_tid);
pthread_mutex_unlock(thread_mutexes[local_tid]);
}
}
线程创建:
int main()
{
int n;
scanf("%d", &n);
printf("Starting signal handler with %d threads...\n",n);
global_mutex = malloc(sizeof(pthread_mutex_t));
firm_mutex = malloc(sizeof(pthread_mutex_t));
thread_mutexes = malloc(n * sizeof(pthread_mutex_t *));
for (int i = 0; i < n; i++) {
thread_mutexes[i] = malloc(sizeof(pthread_mutex_t));
}
attr = malloc(sizeof(pthread_attr_t));
if (pthread_attr_init(attr) != 0 ) {
perror("attrinit\n");
exit(1);
}
if (pthread_attr_setdetachstate (attr,PTHREAD_CREATE_JOINABLE) != 0) {
perror("setdetach\n");
exit(1);
}
for (int i = 0; i < n; i++) {
pthread_t tid;
if (pthread_mutex_init (thread_mutexes[i], 0) != 0) {
perror("mutexinit\n");
exit(1);
}
int *tdata = malloc(sizeof(int));
*tdata = i;
if (pthread_create (&tid, attr, watek, tdata) != 0) {
perror("pthread_create");
exit(1);
}
if (pthread_join (tid, 0) != 0) {
perror("join\n");
exit(1);
}
}
return 0;
}
所以你会认为在启动 10 个线程后,第一个线程应该立即进入休眠状态,同时另一个线程应该开始执行。不幸的是,在使用 10 个线程启动程序后,我得到如下输出:
Starting signal handler with 10 threads...
Starting thread 0
0 locked
sleeping for: 4 seconds
0 woken up!
0 locked
sleeping for: 2 seconds
0 woken up!
0 locked
sleeping for: 3 seconds
0 woken up!
0 locked
sleeping for: 1 seconds
0 woken up!
0 locked
sleeping for: 4 seconds
0 woken up!
0 locked
基本上线程 0 一直在窃取!为什么0休眠时其他线程不执行?
最佳答案
if (pthread_create (&tid, attr, watek, tdata) != 0) {
perror("pthread_create");
exit(1);
}
if (pthread_join (tid, 0) != 0) {
perror("join\n");
exit(1);
}
您正在创建第一个线程,然后在创建下一个线程之前等待 pthread_join
。因此,下一个循环迭代(创建下一个线程)在第一个线程终止之前不会发生。
如果您希望所有线程立即启动,只需在第一个循环中创建并启动它们 - 等待它们稍后完成。
关于c - pthread - sleep 阻止其他线程执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34385187/