有4个线程和1个公共的字符数组。线程1的功能就是向数组输出A,线程2的功能就是向字符输出B,线程3的功能就是向数组输出C,线程4的功能就是向数组输出D。
要求按顺序向数组赋值ABCDABCDABCD,ABCD的个数由输入的参数指定。
输入:
10
输出:
ABCDABCDABCDABCDABCDABCDABCDABCDABCDABCD
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h> //线程库 pthread
#define THREAD_NUMBER 4 /* 线程数 */
void *thread_func(void* arg)
{
int num =(long long)arg; /** sizeof(void*) == 8 and sizeof(int) == 4 (64 bits) */
int res;
int a[]={'A','B','C','D'};
printf("%c", a[num]);
pthread_exit(NULL);
}
int main()
{
pthread_t thread[THREAD_NUMBER];
int num, res;
int t;
/*输入进程执行的次数*/
scanf("%d",&t);
for(int i=0;i<t;i++){
for (num = 0; num < THREAD_NUMBER; num++)
{
/*创建线程*/
res = pthread_create(&thread[num], NULL, thread_func, (void*)(long long)num);
/*创建失败*/
if (res != 0)
{
exit(res);
}
/*对应的线程结束后才返回,下个线程才能继续运行*/
pthread_join(thread[num], NULL);
}
}
return 0;
}