前面的选择题那些跳过,直接看最后的编程题。第三题(某培训机构的练习题):子线程循环 10 次,接着主线程循环 100 次,接着又回到子线程循环 10 次,接着再回到主线程又循环 100 次,如此循环50次,试写出代码。第四题(迅雷笔试题):编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推。第五题(Google面试题)有四个线程1、2、3、4。线程1的功能就是输出1,线程2的功能就是输出2,以此类推.........现在有四个文件ABCD。初始都为空。现要让四个文件呈如下格式:A:1 2 3 4 1 2....B:2 3 4 1 2 3....C:3 4 1 2 3 4....D:4 1 2 3 4 1....请设计程序。
第六题生产者消费者问题这是一个非常经典的多线程题目,题目大意如下:有一个生产者在生产产品,这些产品将提供给若干个消费者去消费,为了使生产者和消费者能并发执行,在两者之间设置一个有多个缓冲区的缓冲池,生产者将它生产的产品放入一个缓冲区中,消费者可以从缓冲区中取走产品进行消费,所有生产者和消费者都是异步方式运行的,但它们必须保持同步,即不允许消费者到一个空的缓冲区中取产品,也不允许生产者向一个已经装满产品且尚未被取走的缓冲区中投放产品。第七题读者写者问题这也是一个非常经典的多线程题目,题目大意如下:有一个写者很多读者,多个读者可以同时读文件,但写者在写文件时不允许有读者在读文件,同样有读者读时写者也不能写。第三题、第四题、第五题第一反应用条件变量来实现。第六题和第七题用读写锁来实现。第三题、第四题、第五题和我这篇
linux多线程学习 (见 http://www.linuxidc.com/Linux/2012-05/60858.htm ) 举得那例子很相似,只需要少量修改就能完成要求。不多说,直接上代码。
第四题代码:
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <unistd.h>
- #include <string.h>
- //#define DEBUG 1
- #define NUM 3
-
- int n=0;
- pthread_mutex_t mylock=PTHREAD_MUTEX_INITIALIZER;
- pthread_cond_t qready=PTHREAD_COND_INITIALIZER;
- void * thread_func(void *arg)
- {
- int param=(int)arg;
- char c="A"+param;
- int ret,i=0;
- for (; i < 10; i++)
- {
- pthread_mutex_lock(&mylock);
- while (param != n)
- {
- #ifdef DEBUG
- printf("thread %d waiting
", param);
- #endif
- ret = pthread_cond_wait(&qready, &mylock);
- if (ret == 0)
- {
- #ifdef DEBUG
- printf("thread %d wait success
", param);
- #endif
- } else
- {
- #ifdef DEBUG
- printf("thread %d wait failed:%s
", param, strerror(ret));
- #endif
- }
- }
- // printf("%d ",param+1);
- printf("%c ",c);
- n=(n+1)%NUM;
- pthread_mutex_unlock(&mylock);
- pthread_cond_broadcast(&qready);
- }
- return (void *)0;
- }
- int main(int argc, char** argv) {
-
- int i=0,err;
- pthread_t tid[NUM];
- void *tret;
- for(;i<NUM;i++)
- {
- err=pthread_create(&tid[i],NULL,thread_func,(void *)i);
- if(err!=0)
- {
- printf("thread_create error:%s
",strerror(err));
- exit(-1);
- }
- }
- for (i = 0; i < NUM; i++)
- {
- err = pthread_join(tid[i], &tret);
- if (err != 0)
- {
- printf("can not join with thread %d:%s
", i,strerror(err));
- exit(-1);
- }
- }
- printf("
");
- return 0;
- }
运行结果:
第五题:选项A,代码只需要将NUM改为4,printf("%c ",c)改为printf("%d ",param+1);即可执行结果如下:
选项B,将全局变量n改为1
选项C,将全局变量n改为2
选项D,将全局变量n改为3