#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
char* data[5];//字符指针数组,存人名
int size = 0;//元素数量
//pthread_mutex_t lock;//1 定义互斥
sem_t sem;
void* task(void* p){
//pthread_mutex_lock(&lock);//3 加锁
sem_wait(&sem);
char* name = (char*)p;
data[size] = name;//data[1] = "gy",cpu归id2
usleep(100000);//data[1] = "zf",cpu让出来
size++;
sem_post(&sem);
//pthread_mutex_unlock(&lock);//5 解锁
}//size = 3
int main(){
data[size] = "liubei"; size++;
sem_init(&sem,0,1);
//pthread_mutex_init(&lock,0);//2 初始化
pthread_t id1,id2;
pthread_create(&id1,0,task,"guanyu");
pthread_create(&id2,0,task,"zhangfei");
pthread_join(id1,0); pthread_join(id2,0);
//pthread_mutex_destroy(&lock);//6 销毁
sem_destroy(&sem);
int i;
for(i=0;i<size;i++) printf("%s\n",data[i]);
}
jion
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
void* task(void* p){//传参时可以把整数当地址传进来
int i = (int)p;
printf("i=%d\n",i); }
void* task1(void* p){//在线程中保证传入的地址有效
sleep(1);
int* pi = (int*)p; printf("%d\n",*pi); }
int main(){
pthread_t id; int x = 100;
int res = pthread_create(&id,0,task,(void*)x);
if(res) printf("%s\n",strerror(res));//判断出错
pthread_join(id,0);//main线程等待task
int* pp = malloc(4); *pp = 100;
pthread_create(&id,0,task1,(void*)pp);
free(pp); pthread_join(id,0);
}
#include <stdio.h>
#include <pthread.h>
char* data[5];//字符指针数组,存人名
int size = 0;//元素数量
pthread_mutex_t lock;//1 定义互斥
void* task(void* p){
pthread_mutex_lock(&lock);//3 加锁
char* name = (char*)p;
data[size] = name;//data[1] = "gy",cpu归id2
usleep(100000);//data[1] = "zf",cpu让出来
size++;
pthread_mutex_unlock(&lock);//5 解锁
}//size = 3
int main(){
data[size] = "liubei"; size++;
pthread_mutex_init(&lock,0);//2 初始化
pthread_t id1,id2;
pthread_create(&id1,0,task,"guanyu");
pthread_create(&id2,0,task,"zhangfei");
pthread_join(id1,0); pthread_join(id2,0);
pthread_mutex_destroy(&lock);//6 销毁
int i;
for(i=0;i<size;i++) printf("%s\n",data[i]);
}