level 6
#include<pthread.h>
#include<stdio.h>
#include<unistd.h>
//定义锁和数据
typedef struct {
int data;
pthread_mutex_t data_lock;
} Data;
Data Number = { 0, 0 };
//定义一个多线程函数,
void *thread_add(void *arg) {
int i = 100;
//循环争夺锁
while (i--) {
//上锁
usleep(10); pthread_mutex_lock(&Number.data_lock);
Number.data++;
printf("线程%d抢夺成功\n", (int)arg);
//释放锁
pthread_mutex_unlock(&Number.data_lock);
} }
int main() {
pthread_t tids[10];
int i = 10, result = 0;
pthread_mutex_init(&Number.data_lock, NULL);
while (--i) {
if (!pthread_create(&tids[i], NULL, thread_add, (void *)i)) {
//pthread_join(tids[i], NULL);
printf("启动线程%d成功\n", i);
} else
printf("启动线程失败:%d", i);
}
for(i=0;i<10;i++)
pthread_join(tids[i],NULL);
return 0;
}
2017年10月11日 13点10分
3
thread_add有返回类型没有显式return,是个问题
2017年10月11日 17点10分
@不知者来此 看编译器的容错吧,按标准肯定要返回的
2017年10月11日 23点10分