- 论坛徽章:
- 0
|
最近开始使用linux下的pthread库进行多线程编程,编写了一个很简单的程序,源代码如下:
#include<pthread.h>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#define THREAD_NUM 500
pthread_mutex_t count_lock;
pthread_cond_t count_nonzero;
unsigned count=0;
void * decrement_count(void * arg)
{
//printf("decrementn");
pthread_mutex_lock(&count_lock);
sleep(10);
while(count==0)
pthread_cond_wait(&count_nonzero,&count_lock);
count=count-1;
printf("This is inside the decrement function: %dn",count);
pthread_mutex_unlock(&count_lock);
return NULL;
}
void * increment_count(void * arg)
{
sleep(10);
//printf("incrementn");
pthread_mutex_lock(&count_lock);
if(count==0)
pthread_cond_signal(&count_nonzero);
count=count+1;
printf("This is inside the increment function: %dn",count);
pthread_mutex_unlock(&count_lock);
return NULL;
}
int main(void)
{
pthread_t thread[THREAD_NUM];
//void * exit_status;
memset(thread,0,sizeof(thread));
pthread_mutex_init(&count_lock,NULL);
pthread_cond_init(&count_nonzero,NULL);
int i=0;
for(i=0;i<THREAD_NUM;i++)
{
if(i%2==0)
{
if(pthread_create(&(thread[i]),NULL,decrement_count,NULL)!=0)
perror("decrement ");
}
else
{
if(pthread_create(&(thread[i]),NULL,increment_count,NULL)!=0)
perror("increment");
}
}
for(i=0;i<THREAD_NUM;i++)
{
if(thread[i]!=0)
pthread_join(thread[i],NULL);//&exit_status);
}
pthread_cond_destroy(&count_nonzero);
return 0;
}
在红帽9下使用gcc content.c -o content -Wall -lpthread 编译,没有发现任何问题,但是运行的时间,结果却为:
decrement : Cannot allocate memory
increment: Cannot allocate memory
decrement : Cannot allocate memory
increment: Cannot allocate memory
decrement : Cannot allocate memory
increment: Cannot allocate memory
decrement : Cannot allocate memory
increment: Cannot allocate memory
decrement : Cannot allocate memory
increment: Cannot allocate memory
decrement : Cannot allocate memory
increment: Cannot allocate memory
decrement : Cannot allocate memory
increment: Cannot allocate memory
请各位高手给看看是什么原因,好吗?着急期待中,非常感谢 |
|