Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
#include <stdio.h>
#include <pthread.h>
static int counter;
void worker()
{
int i;
for (i = 1; i <= 10; i++)
counter++;
}
void* f(void *p)
{
worker();
}
int main()
{
int i, r[22] = {};
for(i = 0; i < 1000000 && counter != 2; ++i)
{
pthread_t t1, t2;
counter = 0;
pthread_create(&t1, NULL, f, NULL);
pthread_create(&t2, NULL, f, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
++r[counter];
}
for(i = 0; i < 22; ++i)
printf("%d:\t%d\n", i, r[i]);
}
worker:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
movq %rsp, %rbp
.cfi_offset 6, -16
.cfi_def_cfa_register 6
movl $1, -4(%rbp)
jmp .L2
.L3:
movl counter(%rip), %eax
addl $1, %eax
movl %eax, counter(%rip)
addl $1, -4(%rbp)
.L2:
cmpl $10, -4(%rbp)
jle .L3
leave
ret
.cfi_endproc
static int together;
void* f(void *p)
{
__sync_add_and_fetch(&together,1);
while(__sync_add_and_fetch(&together,0) < 2);
worker();
}
f:
.LFB1:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
movq %rsp, %rbp
.cfi_offset 6, -16
.cfi_def_cfa_register 6
subq $8, %rsp
movq %rdi, -8(%rbp)
lock addl $1, together(%rip)
.L6:
movl $0, %edx
movl %edx, %eax
lock xaddl %eax, together(%rip)
addl %edx, %eax
cmpl $1, %eax
jle .L6
movl $0, %eax
call worker
leave
ret
.cfi_endproc
2: 1 3: 1 4: 1 6: 4 7: 1 8: 9 9: 5 10: 7044 11: 99 12: 56 13: 98 14: 130 15: 350 16: 144 17: 291 18: 473 19: 304 20: 989
Решите уравнение:
2? 3 = x
где? — какая-то операция
Чему будет равен x и почему?
История двух нитей