I imagine first come first served? Unless there are more sinister reasons for allocating codes to airlines.
South African Airways (1934) predates Singapore Airlines (1972 as independent entity), so SAA got first divs on SA.
Air China (as CAAC, 1949) got head start on China Airlines (1959) but not Air Canada (1936) so the allocations were AC, CA and CI.
Canadian Pacific (1942) predates Cathay Pacific (1946) so got first divs on CP? I have no idea why Cathay went for the X when P was not available - perhaps the other obvious choice (A?) also became unavailable due to CAAC application so Cathay management thought what the hell? Might also have something to do with one of the founders being from the land of XXXX.