我有以下代码(我删除了一些不相关的部分)
使用此代码,我可以使“connect_ip”中的线程不再启动,但当前线程仍在运行,我也想停止它们(仅限“connect_ip”中的线程)
struct domain_list {
char domain[20];
struct domain_list * next;
};
typedef struct arg_struct {
unsigned long ip;
char domain[30];
int X;
int stop;
}arg_struct;
struct domain_list * first_domain = NULL;
int main()
{
//loading into structure from file code is missing
for(i = 0 ; i < number_thread; i++)
{
if(pthread_create(&thread_id[i],NULL,&start,NULL) != 0)
{
i--;
fprintf(stderr,RED "\nError in creating thread\n" NONE);
}
}
for(i = 0 ; i < number_thread; i++)
if(pthread_join(thread_id[i],NULL) != 0)
{
fprintf(stderr,RED "\nError in joining thread\n" NONE);
}
}
void * start(void * data)
{
unsigned long ip = 0xffffffff;
char ip[20];
while (!feof(INFILE))
{
if (fgets(ip,sizeof(ip),INFILE) != NULL)
{
if (strlen(ip) < 8)
break;
if (ip[strlen (ip) - 1] == '\n')
ip[strlen (ip) - 1] = '\0';
ip = ntohl((unsigned long)inet_addr(ip));
}
connect_ip(ip);
}
return NULL;
}
void connect_ip(unsigned long ip)
{
struct domain_list * curr_domain = first_domain;
int exit=0,stop=0;
while(curr_domain)
{
for(t = 0 ; t < ip_thread; t++)
{
pthread_mutex_lock(&thrd_list);
arg_struct *args = calloc(1, sizeof(*args));
strncpy(args->domain,curr_domain->domain,sizeof(args->domain) - 1);
args->ip = ip;
args->X = ex;
args->stop = stop;
pthread_mutex_unlock(&thrd_list);
if(pthread_create(&thread_id[t],NULL,checkip,args) != 0)
{
t--;
fprintf(stderr,RED "\nError in creating thread\n" NONE);
}
else
{
pthread_mutex_lock(&thrd_list);
if(curr_domain->next != NULL)
curr_domain = curr_domain->next;
else
exit = 1;
pthread_mutex_unlock(&thrd_list);
}
}
for(t = 0 ; t < ip_thread; t++)
{
void *join_result;
if(pthread_join(thread_id[t],&join_result) != 0)
{
fprintf(stderr,RED "\nError in joining thread\n" NONE);
}
else
{
arg_struct *args = join_result;
stop = args->stop;
free(args);
}
}
if (exit == 1 || stop == 1)
break;
}//end while
}
void *checkip(void *arguments)
{
arg_struct *args = arguments;
if (args->X == 1)
return args;
int sock = 0,ex = 0,ret = 0;
struct in_addr t_in;
t_in.s_addr = ntohl(args->ip);
sock = check_port(args->ip,80);
if(sock == -1)
{
args->X = 1;
return args;
}
//some code missing
if(ret == 1)
args->stop = 1;
return args;
}
第一个问题是如何在 void "checkip" 中的 ret = 1 时使 "connect_ip" 中的所有线程停止并且不影响 "start" void 中的其他线程?
第二个问题是在这种情况下如何正确使用 pthread_mutex_lock 以使“start”中的线程和“connect_ip”中的线程弄乱数据?