我写了使用的线程在Linux C ++程序的代码。 但它失败了一段时间后,我不知道为什么。 我觉得有可能是内存泄露的地方。 这是一个简化的版本:
#include <stdlib.h>
#include <iostream>
#include <stdio.h>
#include <pthread.h>
#include <signal.h>
using namespace std;
#define MAX_THREADS 20
#define THREAD_STACK 100000
pthread_t pid[MAX_THREADS];
unsigned thread_args[MAX_THREADS][2];
volatile unsigned thread_number = 0;
void* TaskCode(void* parg)
{
unsigned a = ((unsigned *)parg)[0];
unsigned b = ((unsigned *)parg)[1];
for(int i = 0; i < 1000; i++)
;
cout<< "\n\n" << a << " " << b << "\n\n";
thread_number--;
return 0;
}
void Action(unsigned long a,unsigned b)
{
if(thread_number >= MAX_THREADS)
return;
pthread_attr_t attrs;
pthread_attr_init(&attrs);
pthread_attr_setstacksize(&attrs, THREAD_STACK);
thread_args[thread_number][0] = a;
thread_args[thread_number][1] = b;
if(pthread_create(&pid[thread_number],&attrs, TaskCode, (void*) thread_args[thread_number]) != 0)
{
cout<< "\n\n" "new thread failed. thread number:" << thread_number << "\n\n";
for(unsigned i = 0; i < thread_number; i++)
pthread_kill(pid[i], SIGSTOP);
}
thread_number++;
}
int main()
{
int a = 0;
while(true)
{
for(int i = 0; i < 1000; i++)
;
Action(time(0),1);
}
cout<< "\n\nunexpected end\n\n";
}
它出什么问题了?
编辑:作为建议我改变了代码:
#include <stdlib.h>
#include <iostream>
#include <stdio.h>
#include <pthread.h>
#include <signal.h>
using namespace std;
#define MAX_THREADS 20
#define THREAD_STACK 100000
pthread_t pid[MAX_THREADS];
unsigned thread_args[MAX_THREADS][2];
volatile unsigned thread_number = 0;
pthread_mutex_t mutex_;
void* TaskCode(void* parg)
{
unsigned a = ((unsigned *)parg)[0];
unsigned b = ((unsigned *)parg)[1];
for(int i = 0; i < 1000; i++)
;
cout<< "\n\n" << a << " " << b << "\n\n";
pthread_mutex_lock(&mutex_);
thread_number--;
pthread_mutex_unlock(&mutex_);
return 0;
}
void Action(unsigned long a,unsigned b)
{
if(thread_number >= MAX_THREADS)
return;
pthread_attr_t attrs;
pthread_attr_init(&attrs);
pthread_attr_setstacksize(&attrs, THREAD_STACK);
thread_args[thread_number][0] = a;
thread_args[thread_number][1] = b;
if(pthread_create(&pid[thread_number],&attrs, TaskCode, (void*) thread_args[thread_number]) != 0)
{
cout<< "\n\n" "new thread failed. thread number:" << thread_number << "\n\n";
for(unsigned i = 0; i < thread_number; i++)
pthread_kill(pid[i], SIGSTOP);
}
pthread_mutex_lock(&mutex_);
thread_number++;
pthread_mutex_unlock(&mutex_);
}
int main()
{
int a = 0;
pthread_mutex_init(&mutex_, NULL);
while(true)
{
for(int i = 0; i < 1000; i++)
;
Action(time(0),1);
}
pthread_mutex_destroy(&mutex_);
cout<< "\n\nunexpected endn\n";
}
但仍然是失败。