当其中一个线程在 C++ 中使用 pthread 被杀死时,我如何保持进程的存活
How I can keep alive the process while one of its threads is killed using pthread in C++?
我在 c++ 中使用 pthread 编写了一个包含 3 个线程的程序,我想在线程 1 被杀死时保持进程的活动状态。 这是我的程序:
#include <unistd.h>
#include <pthread.h>
#include <iostream>
using namespace std;
int a = 0;
void *func (void *arg)
{
int c = a++;
cout << "start thread " << c << endl;
if (c == 1) //I wrote this to thread1 crashes and be killed.
{
int d = 0;
d = 10 / d;
}
cout << "end thread " << c << endl;
}
int main ()
{
pthread_t tid1, tid2, tid3;
pthread_create (&tid1, 0, func, 0);
sleep (1);
pthread_create (&tid2, 0, func, 0);
sleep (1);
pthread_create (&tid3, 0, func, 0);
sleep (10);
return 0;
}
当我使用"g++ a.cpp-lpthread"运行时,输出如下所示:
start thread 0
end thread 0
start thread 1
Floating point exception (core dumped)
这意味着当线程 1 被杀死时,整个进程将被杀死。 有没有办法在进程的一个线程被杀死时保持活动状态?我需要它,因为我想使用进程的其他线程,但是任何线程都被杀死。
请注意,我不想使用异常处理来避免杀死线程。
我通过忽略FPE信号解决了我的问题。这是我的新程序:
#include <unistd.h>
#include <pthread.h>
#include <iostream>
#include <signal.h>
using namespace std;
int a = 0;
void sig_func(int sig)
{
//some code we want execute when signal recieves, or nothing.
}
void *func (void *arg)
{
int c = a++;
cout << "start thread " << c << endl;
if (c == 1)
{
int d = 0;
d = 10 / d;
}
cout << "end thread " << c << endl;
}
int main ()
{
pthread_t tid1, tid2, tid3;
signal(SIGFPE,sig_func);
pthread_create (&tid1, 0, func, 0);
sleep (1);
pthread_create (&tid2, 0, func, 0);
sleep (1);
pthread_create (&tid3, 0, func, 0);
sleep (10);
return 0;
}
它的输出是这样的:
start thread 0
end thread 0
start thread 1
start thread 2
end thread 2
这意味着当 thread1 被杀死时,整个进程不会被杀死,下一个线程可以运行它们的函数。
您可能希望使用同步机制,例如在多个线程之间共享的信号量(使用 sem_wait((,sem_post(((来诱导延迟。
另一种方法是在 func(( 中使用 while(1( 和 sleep((,但在唤醒时消耗 CPU 周期。
相关文章:
- boost::进程间消息队列引发错误
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 是否可以通过C++扩展强制多个python进程共享同一内存
- IPC使用多个管道和分支进程来运行Python程序
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 异常属于C++中的线程还是进程
- WMI检测进程创建事件-c++
- 我可以信任表示整数的浮点或双精度来保持精度吗
- Python中的for循环与C++有何不同
- Constexpr替代了新的放置方式,可以让内存中的对象保持未初始化状态
- 当进程结束时,如何保持由 QProcess 执行的命令?
- 在程序继续C++时保持进程运行
- 当其中一个线程在 C++ 中使用 pthread 被杀死时,我如何保持进程的存活
- 第一个进程保持运行而后续进程仅传递参数的最佳 IPC 方法是什么?
- 将 initialOwner 设置为 TRUE 的 CreateMutex 使创建者进程保持互斥锁,直到完成
- C++ 在进程杀死其父进程后保持进程活动状态
- 如何保持进程运行
- Interprocess::named_upgradable_mutex -如果进程被杀死,则保持锁定状态
- 保持相同数量的子进程
- 守护进程保持一个c++ ostream打开