- 论坛徽章:
- 0
|
ansi C下多线程编程的问题
我想建立多个线程,每个线程都是完成一样的打印任务,但是打印的内容不同。
我建立了互斥锁,但是访问的变量仍然不对,不知是哪里出现错误了,请教大家。
源代码如下:
#include "pthread.h"
#include "sys/time.h"
#include "stdio.h"
#include "stdlib.h"
#define THREAD_MAX_NUM 10
int send_num;
int send_count;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_t thread[THREAD_MAX_NUM];
char test[10][10];
void *sub_thread()
{
pthread_mutex_lock(&mut);
printf("现在在线程%d中\n",send_num);
pthread_mutex_unlock(&mut);
}
int create_thread()
{
int i=0,temp;
pthread_t threadid[THREAD_MAX_NUM];
for(i=0;i<THREAD_MAX_NUM;i++)
{
pthread_create(&thread,NULL,sub_thread,NULL);
pthread_mutex_lock(&mut);
send_num++;
pthread_mutex_unlock(&mut);
}
temp = i;
for(i=0;i<temp;i++)
{
pthread_join(thread,NULL);
printf("Thread %d down\n",i);
}
return i;
}
int main( int argc,char* argv[])
{
int i=0,thnum;
send_num = 0;
printf("Create %d thread \n",THREAD_MAX_NUM);
pthread_mutex_init(&mut,NULL);
thnum = create_thread();
printf("down\n" ;
}
编译运行后执行结果总不是期望中的打出0到9这十个数字哦,请问我还要做什么线程间的协调呢?
这十个线程我想要它同时执行,而不是通过sleep 1秒的形式或一个线程执行完毕后紧接着执行下一个线程的方式哦。 |
|