Chinaunix首页 | 论坛 | 博客
  • 博客访问: 226183
  • 博文数量: 75
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 848
  • 用 户 组: 普通用户
  • 注册时间: 2013-10-08 10:27
文章分类
文章存档

2014年(9)

2013年(66)

我的朋友

分类: C/C++

2013-11-11 14:59:05

  据说是阿里的笔试题,手写还是有难度的,不过思想倒是很简单,无意看到的,原创可是原创_他 ,这小子很自恋,喜欢给自己的博文做评论。
[cpp] view plaincopy
#include  
#include  
#include  
#include  
#include  
#include  
/********************** 
 *程序在不用系统的random函数,生成随机的字符串 
 *同时创建7个线程,每个线程传入一个参数i,既是 
 *字符串数组中的第i各位置与第零个位置的字母交换 
 *不确定那个线程会先到,所以产生的串是随机排列的 
 *对共有的资源chs[]加锁,防止一个字符出现两次 
 * ****************************/  
  
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;  
  
char chs[7] ={'A', 'B', 'C', 'D', 'E', 'F', 'G'};  
void *th_fun(void* arg)  
{  
    int i = *((int *)arg);  
    char temp;  
    pthread_mutex_lock(&mutex);  
    temp = chs[i];  
    chs[i] = chs[0];  
    chs[0] = temp;  
    pthread_mutex_unlock(&mutex);  
  
    sleep(1);  
    return ((void *)0);  
}  
  
int main(void){  
  
    pthread_t th[7];  
    int i = 0;  
  
    while(i<7){  
        if(0!=pthread_create(&th[i], NULL, th_fun, (void *)&i)){  
            fprintf(stderr, "pthread %d:%s\n", i, strerror(errno));  
            exit(1);  
        }  
        i++;  
    }  
    for(i=0;i<7;i++){  
        pthread_join(th[i], NULL);  
    }  
  
    printf("chs:%s\n", chs);  
  
    return 0;  
  
}  
强烈建议,建议CSDN编辑器添加对Tab键的使用功能。TAB TAB 
阅读(1087) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~