C 如何使两个线程交替执行?;
我有两个函数f1()和f2(),我希望执行f1()和f2() 或者,不使用循环:不像这样:循环{ f1(); f2();} 我只想使用线程方法我的代码如下:C 如何使两个线程交替执行?;,c,pthreads,C,Pthreads,我有两个函数f1()和f2(),我希望执行f1()和f2() 或者,不使用循环:不像这样:循环{ f1(); f2();} 我只想使用线程方法我的代码如下: #include<stdio.h> #include<pthread.h> #include<unistd.h> #include<semaphore.h> void *f1(void *vargp); void *f2(void *vargp); static sem_t
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<semaphore.h>
void *f1(void *vargp);
void *f2(void *vargp);
static sem_t mutex;
int main(int argc, char **argv) {
pthread_t tid1, tid2;
sem_init(&mutex, 0, 1);
pthread_create(&tid1, NULL, f1, NULL);
pthread_create(&tid2, NULL, f2, NULL);
sleep(100);
return 0;
}
void *f1(void *vargp) {
pthread_detach(pthread_self());
while (1) {
sem_wait(&mutex);
printf("In f1\n");
sleep(1);
sem_post(&mutex);
}
return NULL;
}
void *f2(void *vargp) {
pthread_detach(pthread_self());
while(1) {
sem_wait(&mutex);
printf("In f2\n");
sleep(1);
sem_post(&mutex);
}
return NULL;
}
#包括
#包括
#包括
#包括
void*f1(void*vargp);
void*f2(void*vargp);
静态扫描互斥;
int main(int argc,字符**argv){
pthread_t tid1,tid2;
sem_init(&mutex,0,1);
pthread_create(&tid1,NULL,f1,NULL);
pthread_create(&tid2,NULL,f2,NULL);
睡眠(100);
返回0;
}
void*f1(void*vargp){
pthread_detach(pthread_self());
而(1){
sem_等待(&mutex);
printf(“在f1\n中”);
睡眠(1);
sem_post(和互斥);
}
返回NULL;
}
void*f2(void*vargp){
pthread_detach(pthread_self());
而(1){
sem_等待(&mutex);
printf(“在f2\n中”);
睡眠(1);
sem_post(和互斥);
}
返回NULL;
}
结果总是打印“在f1中”我该怎么办?提示:条件变量您的代码同时打印“在f1中”和“在f2中”,预期的行为到底是什么,与您得到的行为有什么区别?我仍然不明白您的意思,抱歉,互斥锁设置为1,您的意思是错误的?你能给我更明确的回答吗?谢谢你,我是一个新手man@ShawnI想要像“在f1中”“在f2中”“在f1中”“在bccyv中”这样的结果吗