在下面的代码示例中,程序执行永远不会结束.
它创建一个线程,在终止之前等待全局bool
设置true
.只有一位作家和一位读者.我相信允许循环继续运行的唯一情况是bool
变量是否为false.
这怎么可能是bool
变量,最终处于不一致的状态只是一个作家?
#include <iostream>
#include <pthread.h>
#include <unistd.h>
bool done = false;
void * threadfunc1(void *) {
std::cout << "t1:start" << std::endl;
while(!done);
std::cout << "t1:done" << std::endl;
return NULL;
}
int main()
{
pthread_t threads;
pthread_create(&threads, NULL, threadfunc1, NULL);
sleep(1);
done = true;
std::cout << "done set to true" << std::endl;
pthread_exit(NULL);
return 0;
}
Run Code Online (Sandbox Code Playgroud) 在C程序中,PTHREAD_CANCEL_ASYNCHRONOUS
只要从父线程触发pthread_cancel ,我就会立即取消该线程.但它导致整个过程因Segmentation Fault而崩溃.子线程的工作是从数据库服务器获取一些数据.我的逻辑是,如果它在10秒内没有获取数据,那么该线程应该从父线程中被杀死.
我只想杀死子线程,而不是整个过程.
struct str_thrd_data
{
SQLHANDLE hstmt;
int rc;
bool thrd_completed_flag;
};
void * str_in_thread_call(void *in_str_arg)
{
int thrd_rc;
struct str_thrd_data *str_arg;
str_arg = in_str_arg;
thrd_rc = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
if (thrd_rc != 0)
handle_error_en(thrd_rc, "pthread_setcancelstate");
thrd_rc = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
if (thrd_rc != 0)
handle_error_en(thrd_rc, "pthread_setcancelstate");
thrd_rc = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
if (thrd_rc != 0)
handle_error_en(thrd_rc, "pthread_setcanceltype");
// Code to call SQL Dynamic Query from a Database Server. This takes time more than 10 seconds.
thrd_rc …
Run Code Online (Sandbox Code Playgroud)