I want to create thread to excute the task from external,
however,pthread_create will lead to segmentation fault but the result value is 0.
It also fails if I set thread_function just with a ; and without any other code.
typedef struct {
int socket;
int login_state;
int connect_state;
int send_length;
ATW_TReqParams* thread_aparams;
void (*ATWFtpNotify)(ATW_TReqParams* AParams);
}ThreadData;
pthread_t worker_thread;
ThreadData* thread_data = NULL;
void* thread_function(void* arg) {
if (arg == NULL) {
return NULL;
}
ThreadData* data = (ThreadData*)arg;
while (data != NULL) {
pthread_mutex_lock(&task_mutex);
while (data->ATWFtpNotify == NULL) {
pthread_cond_wait(&task_condition, &task_mutex);
}
if (data->ATWFtpNotify != NULL) {
data->ATWFtpNotify(data);
data->ATWFtpNotify = NULL;
}
pthread_mutex_unlock(&task_mutex);
}
}
int ATWPlusOpen(int AChipNo)
{
int result = 1;
if (thread_data == NULL)
thread_data = (ThreadData*)malloc(sizeof(ThreadData));
if (thread_data != NULL) {
thread_data->socket = -1;
thread_data->login_state = 0;
thread_data->connect_state = 0;
thread_data->thread_aparams = NULL;
thread_data->ATWFtpNotify = NULL;
result = pthread_create(&worker_thread, NULL, thread_function, thread_data);
}
return result;
}
One bug is that your thread callback lacks a
returnin some of the execution paths. Meaning it will likely crash each time the thread finishes. If you enable compiler warnings and pay attention to them, then this bug would have been spotted. There could be other bugs as well.