typedef struct
{
int count;
pthread_mutex_t mutex;
} Counter;
typedef struct
{
int countA;
int countB;
pthread_mutex_t mutex;
} Counter2;
void* TFa();
void* TFb();
Counter *cA;
Counter *cB;
Counter2 *c;
sem_t *S1, *S2;
int main(int argc, char **argv)
{
S1 = (sem_t *) malloc(sizeof(sem_t));
S2 = (sem_t *) malloc(sizeof(sem_t));
sem_init(S1,0,1);
sem_init(S2,0,1);
int n = atoi(argv[1]);
pthread_t *t1;
pthread_t *t2;
cA= (Counter *) malloc (sizeof(Counter));
cB= (Counter *) malloc (sizeof(Counter));
c= (Counter2 *) malloc (sizeof(Counter2));
cA->count =0;
cB->count =0;
c-> countA =0;
c-> countB =0;
pthread_mutex_init(&cA->mutex, NULL);
pthread_mutex_init(&cB->mutex, NULL);
pthread_mutex_init(&c->mutex, NULL);
t1 = malloc(sizeof(pthread_t)*n);
t2 = malloc((sizeof(pthread_t)*2*n));
for(int i=0; i<n; i++){
pthread_create(&t1[i], NULL, TFa, NULL);
for(int i=0; i<n; i++){
pthread_create(&t2[i], NULL, TFb, NULL);
pthread_exit(NULL);
return 0;
}
void* TFa()
{
pthread_mutex_lock(&cA ->mutex);
int num = cA->count;
cA->count++;
pthread_mutex_unlock(&cA->mutex);
pthread_mutex_lock (&c->mutex);
if(c->countA ==0 && c->countB ==2 )
{
printf("A%d 1n", num);
c->countA =0;
c->countB=0;
sem_post(S1);
pthread_mutex_unlock(&c->mutex);
}
else if(c->countA ==0 && c->countB <2)
{
printf("A%d \n",num);
c->countA ++;
pthread_mutex_unlock(&c->mutex);
}
else
{
pthread_mutex_unlock(&c->mutex);
sem_wait(S1);
pthread_mutex_lock(&c->mutex);
printf("A%d \n", num);
c->countA++;
pthread_mutex_unlock(&c->mutex);
}
pthread_exit(NULL);
}
void* TFb()
{
pthread_mutex_lock(&cB->mutex);
int num = cB->count;
cB->count++;
pthread_mutex_unlock(&cB->mutex);
pthread_mutex_lock(&c->mutex);
if(c->countA ==1 && c->countB ==1)
{
printf("B%d \n", num);
c->countA =0;
c->countB=0;
sem_post(S2);
sem_post(S2);
pthread_mutex_unlock(&c->mutex);
}
else if(c->countA <2 && c->countB ==0)
{
printf("B%d \n", num);
c->countB++;
pthread_mutex_unlock(&c->mutex);
}
else
{
phtread_mutex_unlock(&c->mutex);
sem_wait(S2);
pthread_mutex_lock(&c->mutex);
printf("B%d \n", num);
c->countB++;
pthread_mutex_unlock(&c->mutex);
}
pthread_exit(NULL);
}
我对这个小程序有疑问:
使用生成n的Pthreads在C语言中实现并发程序 线程th_A执行代码A,2 * n个线程th_B执行代码B. 主线程从命令行获取参数n,并在没有的情况下终止 等待它创建的线程的终止。 两个线程只是打印相应的字符,然后是它们的顺序 创建号(th_A从0到n-1,th_B从0到2 * n-1)。 两个B和一个A字符打印后,无论哪个顺序,最后一个 打印线程必须打印'\ n'字符。
但它没有编译,我不理解方式。你有一些提示吗?
答案 0 :(得分:0)
for(int i=0; i<n; i++){
pthread_create(&t1[i], NULL, TFa, NULL);
for(int i=0; i<n; i++){
pthread_create(&t2[i], NULL, TFb, NULL);
这些{
没有匹配的}
。
phtread_mutex_unlock(&c->mutex);
您写了p ht 而不是pthread
。
有了这两个修复程序和缺少的#include
,它就会编译。